'use client'

import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import {
  Building2, CalendarDays, Coins, GitBranch, Landmark, Layers3,
  Plus, RefreshCcw, Save, ShieldCheck, SlidersHorizontal,
} from 'lucide-react'

import { Button } from '@/components/ui/button'
import { DataTable, type Column } from '@/components/ui/data-table'
import { KpiCard } from '@/components/ui/kpi-card'
import { Modal } from '@/components/ui/modal'
import { PageHeader } from '@/components/ui/page-header'
import { SectionCard } from '@/components/ui/section-card'
import { StatusBadge, type StatusTone } from '@/components/ui/status-badge'
import { ENDPOINTS } from '@/constants/endpoints'
import { api } from '@/lib/api'

type Entity = Record<string, any>
type Lang = 'ar' | 'en'
type TabId = 'companies' | 'fiscal' | 'accounts' | 'types' | 'karats' | 'units' | 'opening'

const tabMeta: Array<{ id: TabId; icon: any }> = [
  { id: 'companies', icon: Building2 },
  { id: 'fiscal', icon: CalendarDays },
  { id: 'accounts', icon: GitBranch },
  { id: 'types', icon: Layers3 },
  { id: 'karats', icon: Coins },
  { id: 'units', icon: Landmark },
  { id: 'opening', icon: ShieldCheck },
]

const text = {
  en: {
    title: 'Accounting settings',
    description: 'Sprint 2 workspace for company setup, fiscal periods, chart of accounts, account types, karats, units, and opening-balance design.',
    finance: 'Finance and audit',
    refresh: 'Refresh',
    new: 'New',
    create: 'Create',
    cancel: 'Cancel',
    save: 'Save',
    saved: 'Saved',
    actionCompleted: 'Action completed',
    companies: 'Companies',
    fiscal: 'Fiscal periods',
    accounts: 'Chart of accounts',
    types: 'Account types',
    karats: 'Karats',
    units: 'Gold units',
    opening: 'Opening balances',
    fiscalYears: 'Fiscal years',
    latestPeriods: 'Periods for latest loaded year',
    coaAccounts: 'COA accounts',
    code: 'Code',
    name: 'Name',
    status: 'Status',
    nature: 'Nature',
    karat: 'Karat',
    purityRatio: 'Purity ratio',
    gramsFactor: 'Grams factor',
    type: 'Type',
    posting: 'Posting',
    year: 'Year',
    range: 'Range',
    period: 'Period',
    periods: 'Periods',
    open: 'Open',
    close: 'Close',
    reopen: 'Reopen',
    company: 'Company',
    accountType: 'Account type',
    allowPosting: 'Allow posting',
    normalBalance: 'Normal balance',
    debit: 'Debit',
    credit: 'Credit',
    yes: 'Yes',
    no: 'No',
    arabicName: 'Arabic name',
    englishName: 'English name',
    sortOrder: 'Sort order',
    parentId: 'Parent ID',
    startDate: 'Start date',
    endDate: 'End date',
    createTitle: 'Create {{label}}',
    openingWorkflow: 'Opening balance workflow design',
    step: 'Step',
    guard: 'Guard',
    draftBatch: 'Draft batch',
    draftGuard: 'Company, fiscal year, period, account, currency/purity, and amount are required.',
    validate: 'Validate',
    validateGuard: 'Debit and credit totals must balance before submit.',
    approve: 'Approve',
    approveGuard: 'Maker cannot approve their own batch.',
    post: 'Post',
    postGuard: 'Creates an opening journal entry and locks direct edits.',
    active: 'Active',
    inactive: 'Inactive',
    draft: 'Draft',
    closing: 'Closing',
    closed: 'Closed',
    reopened: 'Reopened',
    locked: 'Locked',
  },
  ar: {
    title: 'إعدادات المحاسبة',
    description: 'مساحة عمل لإعداد الشركات والفترات المالية ودليل الحسابات وأنواع الحسابات والعيارات والوحدات وتصميم الأرصدة الافتتاحية.',
    finance: 'المالية والتدقيق',
    refresh: 'تحديث',
    new: 'جديد',
    create: 'إنشاء',
    cancel: 'إلغاء',
    save: 'حفظ',
    saved: 'تم الحفظ',
    actionCompleted: 'تم تنفيذ الإجراء',
    companies: 'الشركات',
    fiscal: 'الفترات المالية',
    accounts: 'دليل الحسابات',
    types: 'أنواع الحسابات',
    karats: 'العيارات',
    units: 'وحدات الذهب',
    opening: 'الأرصدة الافتتاحية',
    fiscalYears: 'السنوات المالية',
    latestPeriods: 'فترات آخر سنة محملة',
    coaAccounts: 'حسابات الدليل',
    code: 'الكود',
    name: 'الاسم',
    status: 'الحالة',
    nature: 'الطبيعة',
    karat: 'العيار',
    purityRatio: 'نسبة النقاوة',
    gramsFactor: 'معامل الجرام',
    type: 'النوع',
    posting: 'الترحيل',
    year: 'السنة',
    range: 'النطاق',
    period: 'الفترة',
    periods: 'الفترات',
    open: 'فتح',
    close: 'إغلاق',
    reopen: 'إعادة فتح',
    company: 'الشركة',
    accountType: 'نوع الحساب',
    allowPosting: 'السماح بالترحيل',
    normalBalance: 'الرصيد الطبيعي',
    debit: 'مدين',
    credit: 'دائن',
    yes: 'نعم',
    no: 'لا',
    arabicName: 'الاسم بالعربية',
    englishName: 'الاسم بالإنجليزية',
    sortOrder: 'ترتيب العرض',
    parentId: 'معرف الحساب الأب',
    startDate: 'تاريخ البداية',
    endDate: 'تاريخ النهاية',
    createTitle: 'إنشاء {{label}}',
    openingWorkflow: 'تصميم مسار الأرصدة الافتتاحية',
    step: 'الخطوة',
    guard: 'الضابط',
    draftBatch: 'مسودة الدفعة',
    draftGuard: 'الشركة والسنة المالية والفترة والحساب والعملة أو العيار والمبلغ مطلوبة.',
    validate: 'التحقق',
    validateGuard: 'يجب توازن إجمالي المدين والدائن قبل الإرسال.',
    approve: 'اعتماد',
    approveGuard: 'لا يمكن لمنشئ الدفعة اعتمادها.',
    post: 'ترحيل',
    postGuard: 'ينشئ قيد افتتاحي ويمنع التعديل المباشر.',
    active: 'نشط',
    inactive: 'غير نشط',
    draft: 'مسودة',
    closing: 'قيد الإغلاق',
    closed: 'مغلق',
    reopened: 'معاد فتحها',
    locked: 'مقفل',
  },
} satisfies Record<Lang, Record<string, string>>

const statusTone: Record<string, StatusTone> = {
  active: 'success',
  inactive: 'neutral',
  draft: 'neutral',
  open: 'success',
  closing: 'warning',
  closed: 'danger',
  reopened: 'warning',
  locked: 'danger',
}

const unwrap = <T,>(value: any): T => (value?.data?.data ?? value?.data ?? value) as T

export default function AccountingSettingsPage() {
  const { i18n } = useTranslation()
  const language: Lang = i18n.language.startsWith('ar') ? 'ar' : 'en'
  const t = text[language]
  const [active, setActive] = useState<TabId>('companies')
  const [loading, setLoading] = useState(false)
  const [companies, setCompanies] = useState<Entity[]>([])
  const [years, setYears] = useState<Entity[]>([])
  const [periods, setPeriods] = useState<Entity[]>([])
  const [accounts, setAccounts] = useState<Entity[]>([])
  const [accountTypes, setAccountTypes] = useState<Entity[]>([])
  const [karats, setKarats] = useState<Entity[]>([])
  const [units, setUnits] = useState<Entity[]>([])
  const [modal, setModal] = useState<null | TabId>(null)
  const [form, setForm] = useState<Record<string, string>>({})

  const tabs = useMemo(() => tabMeta.map(tab => ({ ...tab, label: t[tab.id] })), [t])

  const loadAll = useCallback(async () => {
    setLoading(true)
    try {
      const [companyRes, yearsRes, accountsRes, typesRes, karatsRes, unitsRes] = await Promise.all([
        api.get(ENDPOINTS.COMPANIES.LIST, { params: { limit: 500 } }).catch(() => []),
        api.get(ENDPOINTS.FISCAL.YEARS, { params: { limit: 100 } }).catch(() => []),
        api.get(ENDPOINTS.ACCOUNTS.LIST, { params: { limit: 500 } }).catch(() => []),
        api.get(ENDPOINTS.ACCOUNT_TYPES.LIST, { params: { limit: 100 } }).catch(() => []),
        api.get(ENDPOINTS.PURITIES.LIST, { params: { limit: 200 } }).catch(() => []),
        api.get(ENDPOINTS.GOLD_UNITS.LIST, { params: { limit: 200 } }).catch(() => []),
      ])
      const loadedYears = asArray(yearsRes)
      setCompanies(asArray(companyRes))
      setYears(loadedYears)
      setAccounts(asArray(accountsRes))
      setAccountTypes(asArray(typesRes))
      setKarats(asArray(karatsRes))
      setUnits(asArray(unitsRes))
      if (loadedYears[0]?.id) {
        const periodRes = await api.get(ENDPOINTS.FISCAL.YEAR_PERIODS(loadedYears[0].id), { params: { limit: 100 } }).catch(() => [])
        setPeriods(asArray(periodRes))
      } else {
        setPeriods([])
      }
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => { loadAll() }, [loadAll])

  const openCreate = (tab: TabId) => {
    setForm(defaultForm(tab))
    setModal(tab)
  }

  const createEntity = async () => {
    if (!modal) return
    try {
      if (modal === 'companies') await api.post(ENDPOINTS.COMPANIES.CREATE, clean(form))
      if (modal === 'types') await api.post(ENDPOINTS.ACCOUNT_TYPES.CREATE, { ...clean(form), sort_order: Number(form.sort_order || 0) })
      if (modal === 'accounts') await api.post(ENDPOINTS.ACCOUNTS.CREATE, { ...clean(form), allow_posting: form.allow_posting === 'true', is_system: false })
      if (modal === 'karats') await api.post(ENDPOINTS.PURITIES.CREATE, { ...clean(form), karat: Number(form.karat), sort_order: Number(form.sort_order || 0) })
      if (modal === 'units') await api.post(ENDPOINTS.GOLD_UNITS.CREATE, { ...clean(form), sort_order: Number(form.sort_order || 0) })
      if (modal === 'fiscal') await api.post(ENDPOINTS.FISCAL.CREATE_YEAR, clean(form))
      setModal(null)
      toast.success(t.saved)
      await loadAll()
    } catch {
      /* global api interceptor displays details */
    }
  }

  const runFiscal = async (endpoint: string, body: Entity = {}) => {
    await api.post(endpoint, body)
    toast.success(t.actionCompleted)
    await loadAll()
  }

  const stats = useMemo(() => ({
    companies: companies.length,
    fiscal: periods.length,
    accounts: accounts.length,
    karats: karats.length,
  }), [companies.length, periods.length, accounts.length, karats.length])

  const modalTitle = modal ? t.createTitle.replace('{{label}}', t[modal]) : ''

  return (
    <div className="space-y-5">
      <PageHeader
        title={t.title}
        description={t.description}
        breadcrumbs={[{ label: t.finance, href: '#' }, { label: t.title }]}
        actions={<Button variant="outline" onClick={loadAll} isLoading={loading}><RefreshCcw className="h-4 w-4" />{t.refresh}</Button>}
      />

      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <KpiCard label={t.companies} value={String(stats.companies)} icon={Building2} tone="gold" accent />
        <KpiCard label={t.fiscal} value={String(stats.fiscal)} icon={CalendarDays} tone="info" />
        <KpiCard label={t.coaAccounts} value={String(stats.accounts)} icon={GitBranch} tone="success" />
        <KpiCard label={t.karats} value={String(stats.karats)} icon={Coins} tone="warning" />
      </div>

      <div className="flex flex-wrap gap-2 border-b border-border">
        {tabs.map(tab => {
          const Icon = tab.icon
          return (
            <button
              key={tab.id}
              onClick={() => setActive(tab.id)}
              className={`inline-flex h-10 items-center gap-2 border-b-2 px-3 text-sm transition ${active === tab.id ? 'border-gold-500 text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}`}
            >
              <Icon className="h-4 w-4" />{tab.label}
            </button>
          )
        })}
      </div>

      {active === 'companies' && <EntitySection title={t.companies} newLabel={t.new} action={() => openCreate('companies')} columns={companyColumns(t, language)} data={companies} />}
      {active === 'accounts' && <EntitySection title={t.accounts} newLabel={t.new} action={() => openCreate('accounts')} columns={accountColumns(accountTypes, t, language)} data={accounts} />}
      {active === 'types' && <EntitySection title={t.types} newLabel={t.new} action={() => openCreate('types')} columns={typeColumns(t, language)} data={accountTypes} />}
      {active === 'karats' && <EntitySection title={t.karats} newLabel={t.new} action={() => openCreate('karats')} columns={karatColumns(t, language)} data={karats} />}
      {active === 'units' && <EntitySection title={t.units} newLabel={t.new} action={() => openCreate('units')} columns={unitColumns(t, language)} data={units} />}
      {active === 'fiscal' && (
        <div className="grid gap-5 xl:grid-cols-[360px_minmax(0,1fr)]">
          <EntitySection title={t.fiscalYears} newLabel={t.new} action={() => openCreate('fiscal')} columns={yearColumns(runFiscal, t, language)} data={years} />
          <EntitySection title={t.latestPeriods} newLabel={t.new} columns={periodColumns(runFiscal, t, language)} data={periods} />
        </div>
      )}
      {active === 'opening' && <OpeningBalanceDesign labels={t} />}

      <Modal open={!!modal} onClose={() => setModal(null)} title={modalTitle} size="lg">
        <DynamicForm tab={modal} form={form} setForm={setForm} accountTypes={accountTypes} companies={companies} labels={t} language={language} />
        <div className="mt-5 flex justify-end gap-2 border-t border-border pt-4">
          <Button variant="outline" onClick={() => setModal(null)}>{t.cancel}</Button>
          <Button onClick={createEntity}><Save className="h-4 w-4" />{t.save}</Button>
        </div>
      </Modal>
    </div>
  )
}

function EntitySection({ title, newLabel, action, columns, data }: { title: string; newLabel: string; action?: () => void; columns: Column<Entity>[]; data: Entity[] }) {
  return (
    <SectionCard title={title} icon={<SlidersHorizontal className="h-4 w-4 text-gold-600" />} padded={false}>
      <div className="flex justify-end border-b border-border p-3">
        {action && <Button size="sm" onClick={action}><Plus className="h-4 w-4" />{newLabel}</Button>}
      </div>
      <DataTable columns={columns} data={data} rowKey={(row, index) => row.id || String(index)} compact />
    </SectionCard>
  )
}

function DynamicForm({ tab, form, setForm, accountTypes, companies, labels, language }: { tab: TabId | null; form: Record<string, string>; setForm: (next: Record<string, string>) => void; accountTypes: Entity[]; companies: Entity[]; labels: Record<string, string>; language: Lang }) {
  if (!tab) return null
  const update = (key: string, value: string) => setForm({ ...form, [key]: value })
  const fields = fieldsFor(tab, labels)
  return (
    <div className="grid gap-3 md:grid-cols-2">
      {tab === 'accounts' && (
        <>
          <Select label={labels.company} value={form.company_id || ''} onChange={v => update('company_id', v)} options={companies.map(c => ({ value: c.id, label: c.name_en || c.name_ar || c.code }))} />
          <Select label={labels.accountType} value={form.account_type_id || ''} onChange={v => update('account_type_id', v)} options={accountTypes.map(t => ({ value: t.id, label: `${t.code} - ${language === 'ar' ? t.name_ar || t.name_en : t.name_en || t.name_ar}` }))} />
        </>
      )}
      {fields.map(field => (
        <label key={field.key} className="text-xs font-medium">
          {field.label}
          <input
            value={form[field.key] || ''}
            onChange={event => update(field.key, event.target.value)}
            type={field.type || 'text'}
            className="mt-1 h-10 w-full rounded-md border border-border bg-background px-3 text-sm"
          />
        </label>
      ))}
      {tab === 'accounts' && <Select label={labels.allowPosting} value={form.allow_posting || 'false'} onChange={v => update('allow_posting', v)} options={[{ value: 'false', label: labels.no }, { value: 'true', label: labels.yes }]} />}
      {tab === 'types' && <Select label={labels.normalBalance} value={form.normal_balance || 'debit'} onChange={v => update('normal_balance', v)} options={[{ value: 'debit', label: labels.debit }, { value: 'credit', label: labels.credit }]} />}
    </div>
  )
}

function Select({ label, value, onChange, options }: { label: string; value: string; onChange: (value: string) => void; options: Array<{ value: string; label: string }> }) {
  return (
    <label className="text-xs font-medium">
      {label}
      <select value={value} onChange={event => onChange(event.target.value)} className="mt-1 h-10 w-full rounded-md border border-border bg-background px-3 text-sm">
        <option value="">-</option>
        {options.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
      </select>
    </label>
  )
}

function OpeningBalanceDesign({ labels }: { labels: Record<string, string> }) {
  const rows = [
    { step: labels.draftBatch, guard: labels.draftGuard },
    { step: labels.validate, guard: labels.validateGuard },
    { step: labels.approve, guard: labels.approveGuard },
    { step: labels.post, guard: labels.postGuard },
  ]
  return (
    <SectionCard title={labels.openingWorkflow} icon={<ShieldCheck className="h-4 w-4 text-gold-600" />}>
      <DataTable columns={[{ key: 'step', header: labels.step, cell: row => row.step }, { key: 'guard', header: labels.guard, cell: row => row.guard }]} data={rows} rowKey={row => row.step} compact />
    </SectionCard>
  )
}

function asArray(value: any): Entity[] {
  const payload = unwrap<any>(value)
  if (Array.isArray(payload)) return payload
  if (Array.isArray(payload?.items)) return payload.items
  return []
}

function clean(data: Record<string, string>) {
  return Object.fromEntries(Object.entries(data).filter(([, value]) => value !== ''))
}

function statusLabel(value: string | undefined, labels: Record<string, string>) {
  const key = String(value || '').toLowerCase()
  return labels[key] || value || '-'
}

function badge(value: string | undefined, labels: Record<string, string>) {
  const key = String(value || '').toLowerCase()
  const tone = statusTone[key] || 'neutral'
  return <StatusBadge tone={tone} size="sm">{statusLabel(value, labels)}</StatusBadge>
}

const companyColumns = (labels: Record<string, string>, language: Lang): Column<Entity>[] => [
  { key: 'code', header: labels.code, cell: row => <span className="font-mono">{row.code}</span> },
  { key: 'name', header: labels.name, cell: row => language === 'ar' ? row.name_ar || row.name_en : row.name_en || row.name_ar },
  { key: 'status', header: labels.status, cell: row => badge(row.status, labels) },
]

const typeColumns = (labels: Record<string, string>, language: Lang): Column<Entity>[] => [
  { key: 'code', header: labels.code, cell: row => <span className="font-mono">{row.code}</span> },
  { key: 'name', header: labels.name, cell: row => language === 'ar' ? row.name_ar || row.name_en : row.name_en || row.name_ar },
  { key: 'normal', header: labels.nature, cell: row => row.normal_balance === 'credit' ? labels.credit : labels.debit },
  { key: 'status', header: labels.status, cell: row => badge(row.is_active ? 'active' : 'inactive', labels) },
]

const karatColumns = (labels: Record<string, string>, language: Lang): Column<Entity>[] => [
  { key: 'karat', header: labels.karat, cell: row => `${row.karat}K` },
  { key: 'ratio', header: labels.purityRatio, cell: row => row.purity_ratio },
  { key: 'name', header: labels.name, cell: row => language === 'ar' ? row.name_ar || row.name_en : row.name_en || row.name_ar },
  { key: 'status', header: labels.status, cell: row => badge(row.is_active ? 'active' : 'inactive', labels) },
]

const unitColumns = (labels: Record<string, string>, language: Lang): Column<Entity>[] => [
  { key: 'code', header: labels.code, cell: row => <span className="font-mono">{row.code}</span> },
  { key: 'factor', header: labels.gramsFactor, cell: row => row.grams_factor },
  { key: 'name', header: labels.name, cell: row => language === 'ar' ? row.name_ar || row.name_en : row.name_en || row.name_ar },
  { key: 'status', header: labels.status, cell: row => badge(row.is_active ? 'active' : 'inactive', labels) },
]

const accountColumns = (types: Entity[], labels: Record<string, string>, language: Lang): Column<Entity>[] => [
  { key: 'code', header: labels.code, cell: row => <span className="font-mono">{row.code}</span> },
  { key: 'name', header: labels.name, cell: row => language === 'ar' ? row.name_ar || row.name_en : row.name_en || row.name_ar },
  { key: 'type', header: labels.type, cell: row => types.find(t => t.id === row.account_type_id)?.code || '-' },
  { key: 'posting', header: labels.posting, cell: row => row.allow_posting ? labels.yes : labels.no },
  { key: 'status', header: labels.status, cell: row => badge(row.is_active ? 'active' : 'inactive', labels) },
]

const yearColumns = (run: (endpoint: string, body?: Entity) => void, labels: Record<string, string>, language: Lang): Column<Entity>[] => [
  { key: 'name', header: labels.year, cell: row => row.name },
  { key: 'range', header: labels.range, cell: row => `${row.start_date} - ${row.end_date}` },
  { key: 'status', header: labels.status, cell: row => badge(row.status, labels) },
  { key: 'actions', header: '', cell: row => <div className="flex gap-1"><Button size="sm" variant="outline" onClick={() => run(ENDPOINTS.FISCAL.GENERATE_PERIODS(row.id))}>{labels.periods}</Button><Button size="sm" variant="outline" onClick={() => run(ENDPOINTS.FISCAL.OPEN_YEAR(row.id), { reason: language === 'ar' ? 'فتح من واجهة الإعدادات' : 'Opened from settings UI' })}>{labels.open}</Button></div> },
]

const periodColumns = (run: (endpoint: string, body?: Entity) => void, labels: Record<string, string>, language: Lang): Column<Entity>[] => [
  { key: 'number', header: '#', cell: row => row.period_number },
  { key: 'name', header: labels.period, cell: row => row.name },
  { key: 'range', header: labels.range, cell: row => `${row.start_date} - ${row.end_date}` },
  { key: 'status', header: labels.status, cell: row => badge(row.status, labels) },
  { key: 'actions', header: '', cell: row => <div className="flex gap-1"><Button size="sm" variant="outline" onClick={() => run(ENDPOINTS.FISCAL.CLOSE_PERIOD(row.id), { reason: language === 'ar' ? 'إغلاق من واجهة الإعدادات' : 'Closed from settings UI' })}>{labels.close}</Button><Button size="sm" variant="outline" onClick={() => run(ENDPOINTS.FISCAL.REOPEN_PERIOD(row.id), { reopening_reason: language === 'ar' ? 'إعادة فتح من واجهة الإعدادات' : 'Reopened from settings UI' })}>{labels.reopen}</Button><Button size="sm" variant="outline" onClick={() => run(ENDPOINTS.FISCAL.OPEN_PERIOD(row.id), { reason: language === 'ar' ? 'فتح من واجهة الإعدادات' : 'Marked open from settings UI' })}>{labels.open}</Button></div> },
]

function defaultForm(tab: TabId): Record<string, string> {
  if (tab === 'companies') return { code: '', name_ar: '', name_en: '', status: 'active' }
  if (tab === 'types') return { code: '', name_ar: '', name_en: '', normal_balance: 'debit', sort_order: '0' }
  if (tab === 'accounts') return { company_id: '', code: '', name_ar: '', name_en: '', account_type_id: '', parent_id: '', allow_posting: 'false' }
  if (tab === 'karats') return { karat: '', purity_ratio: '', name_ar: '', name_en: '', sort_order: '0' }
  if (tab === 'units') return { code: '', name_ar: '', name_en: '', grams_factor: '', sort_order: '0' }
  if (tab === 'fiscal') return { name: '', start_date: '', end_date: '' }
  return {}
}

function fieldsFor(tab: TabId, labels: Record<string, string>) {
  if (tab === 'companies') return [{ key: 'code', label: labels.code }, { key: 'name_ar', label: labels.arabicName }, { key: 'name_en', label: labels.englishName }, { key: 'status', label: labels.status }]
  if (tab === 'types') return [{ key: 'code', label: labels.code }, { key: 'name_ar', label: labels.arabicName }, { key: 'name_en', label: labels.englishName }, { key: 'sort_order', label: labels.sortOrder, type: 'number' }]
  if (tab === 'accounts') return [{ key: 'code', label: labels.code }, { key: 'name_ar', label: labels.arabicName }, { key: 'name_en', label: labels.englishName }, { key: 'parent_id', label: labels.parentId }]
  if (tab === 'karats') return [{ key: 'karat', label: labels.karat, type: 'number' }, { key: 'purity_ratio', label: labels.purityRatio }, { key: 'name_ar', label: labels.arabicName }, { key: 'name_en', label: labels.englishName }, { key: 'sort_order', label: labels.sortOrder, type: 'number' }]
  if (tab === 'units') return [{ key: 'code', label: labels.code }, { key: 'grams_factor', label: labels.gramsFactor }, { key: 'name_ar', label: labels.arabicName }, { key: 'name_en', label: labels.englishName }, { key: 'sort_order', label: labels.sortOrder, type: 'number' }]
  if (tab === 'fiscal') return [{ key: 'name', label: labels.name }, { key: 'start_date', label: labels.startDate, type: 'date' }, { key: 'end_date', label: labels.endDate, type: 'date' }]
  return []
}
