import { verifySession } from "@/lib/auth";

import { hasEmployeePermission } from "@/lib/employee-permissions";
import { getCurrentLocale, getTranslations } from "@/lib/i18n";
import { getChartOfAccountsWithSeedMerge } from "@/lib/accounting/chart-of-accounts-runtime";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import AddAccountDialog from "@/components/admin/add-account-dialog";
import EditAccountDialog from "@/components/admin/edit-account-dialog";

export default async function ChartOfAccountsPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tAccounting = t.Accounting ?? {};
  const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();  
  if (!user || !hasEmployeePermission(user, settings, 'admin.accounting')) {
    return (
        <div className="text-center">
            <h1 className="text-2xl font-bold">{t.Global.accessDenied}</h1>
            <p>{t.Global.noPermission}</p>
        </div>
    );
  }

  const accounts = await getChartOfAccountsWithSeedMerge();
  const isSystemAdmin = user.role === 'admin';
  const banksParentId = (accounts.find((acc: any) => String(acc?.code || '').trim() === '1120') as any)?.id || '__root__';

  // Group accounts by parent
  const topLevelAccounts = accounts.filter(acc => acc.parentId === null);
  
  const renderAccount = (account: any, level: number = 0) => {
    const children = accounts.filter(acc => acc.parentId === account.id);
    const isHeader = account.type === 'header';
    const rows: any[] = [];
    
    const rowClassName = isHeader ? 'bg-muted/50 font-semibold' : undefined;
    
    rows.push(
      <TableRow key={`row-${account.id}`} className={rowClassName}>
        <TableCell style={{ paddingRight: `${level * 2}rem` }}>
          {account.code}
        </TableCell>
        <TableCell className="font-medium">
          {locale === 'ar' ? account.nameAr : account.nameEn}
        </TableCell>
        <TableCell className="text-center">
          {isHeader ? (
            <Badge variant="secondary">{tAccounting?.header ?? 'عنوان'}</Badge>
          ) : (
            <Badge variant={account.nature === 'debit' ? 'default' : 'outline'}>
              {account.nature === 'debit' ? (tAccounting?.debit ?? 'مدين') : (tAccounting?.credit ?? 'دائن')}
            </Badge>
          )}
        </TableCell>
        {isSystemAdmin && (
          <TableCell className="text-center">
            <EditAccountDialog account={account} accounts={accounts as any[]} />
          </TableCell>
        )}
      </TableRow>
    );
    
    for (const child of children) {
      rows.push(...renderAccount(child, level + 1));
    }
    
    return rows;
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-3xl font-bold">{tAccounting?.chartOfAccounts ?? 'شجرة الحسابات'}</h1>
          <p className="text-muted-foreground">{tAccounting?.chartDescription ?? 'عرض جميع الحسابات المحاسبية في النظام'}</p>
        </div>
        <div className="flex gap-2">
          <AddAccountDialog accounts={accounts} />
          <AddAccountDialog
            accounts={accounts}
            title="إنشاء حساب شيكات واردة"
            triggerLabel="إنشاء 1015 شيكات واردة"
            initialValues={{
              code: '1015',
              nameAr: 'شيكات واردة',
              nameEn: 'Incoming Checks',
              type: 'account',
              nature: 'debit',
              parentId: banksParentId,
            }}
          />
          <AddAccountDialog
            accounts={accounts}
            title="إنشاء حساب شيكات برسم التحصيل"
            triggerLabel="إنشاء 1020 شيكات برسم التحصيل"
            initialValues={{
              code: '1020',
              nameAr: 'شيكات برسم التحصيل',
              nameEn: 'Checks for Collection',
              type: 'account',
              nature: 'debit',
              parentId: banksParentId,
            }}
          />
          <Button asChild>
            <Link href="/admin/accounting/entries">
              {tAccounting?.journalEntries ?? 'القيود اليومية'}
            </Link>
          </Button>
        </div>
      </div>
      
      <Card>
        <CardHeader>
          <CardTitle>{tAccounting?.accountsTree ?? 'تصنيف الحسابات'}</CardTitle>
          <CardDescription>
            {tAccounting?.accountsTreeDescription ?? 'التصنيف الهرمي للحسابات المحاسبية'}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{tAccounting?.accountCode ?? 'رمز الحساب'}</TableHead>
                <TableHead>{tAccounting?.accountName ?? 'اسم الحساب'}</TableHead>
                <TableHead className="text-center">{tAccounting?.accountType ?? 'النوع'}</TableHead>
                {isSystemAdmin && (
                  <TableHead className="text-center">إجراءات</TableHead>
                )}
              </TableRow>
            </TableHeader>
            <TableBody>
              {topLevelAccounts.flatMap(account => renderAccount(account))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
