'use client';

import { useMemo, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { formatCurrency } from '@/lib/currency-formatter';
import {
  type FinancialEntryStatus,
  type FinancialReportAccount,
  type FinancialReportJournalEntry,
  buildBalanceSheetData,
  buildCashBankRows,
  buildCashFlowRows,
  buildIncomeStatementData,
  buildLedgerRows,
  buildTrialBalanceRows,
} from '@/lib/accounting/financial-reporting';

type Props = {
  accounts: FinancialReportAccount[];
  entries: FinancialReportJournalEntry[];
  currencySymbol: string;
  defaultDate: string;
};

function normalizeArabicForSearch(value: string): string {
  return value
    .toLowerCase()
    .replace(/[\u064B-\u0652\u0670]/g, '')
    .replace(/ـ/g, '')
    .replace(/[أإآٱ]/g, 'ا')
    .replace(/ة/g, 'ه')
    .replace(/ى/g, 'ي')
    .replace(/ؤ/g, 'و')
    .replace(/ئ/g, 'ي')
    .replace(/\s+/g, ' ')
    .trim();
}

function matchesSearch(haystack: string, query: string) {
  const normalizedQuery = normalizeArabicForSearch(query);
  if (!normalizedQuery) return true;
  return normalizeArabicForSearch(haystack).includes(normalizedQuery);
}

function ReportStat({ label, value, className = '' }: { label: string; value: string | number; className?: string }) {
  return (
    <div className="rounded-md border p-4">
      <p className="text-sm text-muted-foreground">{label}</p>
      <p className={`text-2xl font-bold ${className}`}>{value}</p>
    </div>
  );
}

export default function FinancialReportsClient({ accounts, entries, currencySymbol, defaultDate }: Props) {
  const fmt = (value: number) => formatCurrency(Number(value || 0), currencySymbol);

  const [trialFromDate, setTrialFromDate] = useState('');
  const [trialToDate, setTrialToDate] = useState(defaultDate);
  const [trialStatus, setTrialStatus] = useState<FinancialEntryStatus>('posted');
  const [trialSearch, setTrialSearch] = useState('');
  const [trialCategory, setTrialCategory] = useState<'all' | 'assets' | 'liabilities' | 'equity' | 'revenues' | 'expenses'>('all');

  const [ledgerFromDate, setLedgerFromDate] = useState('');
  const [ledgerToDate, setLedgerToDate] = useState(defaultDate);
  const [ledgerStatus, setLedgerStatus] = useState<FinancialEntryStatus>('posted');
  const [ledgerSearch, setLedgerSearch] = useState('');
  const [ledgerAccountKey, setLedgerAccountKey] = useState('');

  const [balanceSheetDate, setBalanceSheetDate] = useState(defaultDate);
  const [balanceSheetStatus, setBalanceSheetStatus] = useState<FinancialEntryStatus>('posted');
  const [balanceSheetSearch, setBalanceSheetSearch] = useState('');

  const [incomeFromDate, setIncomeFromDate] = useState('');
  const [incomeToDate, setIncomeToDate] = useState(defaultDate);
  const [incomeStatus, setIncomeStatus] = useState<FinancialEntryStatus>('posted');
  const [incomeSearch, setIncomeSearch] = useState('');

  const [cashFromDate, setCashFromDate] = useState('');
  const [cashToDate, setCashToDate] = useState(defaultDate);
  const [cashStatus, setCashStatus] = useState<FinancialEntryStatus>('posted');
  const [cashSearch, setCashSearch] = useState('');
  const [cashAccountKey, setCashAccountKey] = useState('all');

  const [flowFromDate, setFlowFromDate] = useState('');
  const [flowToDate, setFlowToDate] = useState(defaultDate);
  const [flowStatus, setFlowStatus] = useState<FinancialEntryStatus>('posted');
  const [flowSearch, setFlowSearch] = useState('');
  const [flowCategory, setFlowCategory] = useState<'all' | 'operating' | 'investing' | 'financing'>('all');

  const trialRows = useMemo(() => buildTrialBalanceRows(entries, accounts, {
    fromDate: trialFromDate,
    toDate: trialToDate,
    status: trialStatus,
  }), [entries, accounts, trialFromDate, trialToDate, trialStatus]);

  const filteredTrialRows = useMemo(() => trialRows.filter((row) => {
    const matchesCategory = trialCategory === 'all' || row.category === trialCategory;
    const haystack = [row.accountCode, row.accountName, row.category].join(' ');
    return matchesCategory && matchesSearch(haystack, trialSearch);
  }), [trialRows, trialCategory, trialSearch]);

  const trialTotals = useMemo(() => ({
    debitTotal: filteredTrialRows.reduce((sum, row) => sum + row.debitTotal, 0),
    creditTotal: filteredTrialRows.reduce((sum, row) => sum + row.creditTotal, 0),
    balanceDebit: filteredTrialRows.reduce((sum, row) => sum + row.balanceDebit, 0),
    balanceCredit: filteredTrialRows.reduce((sum, row) => sum + row.balanceCredit, 0),
  }), [filteredTrialRows]);

  const ledgerAccountOptions = useMemo(() => buildTrialBalanceRows(entries, accounts, {
    fromDate: ledgerFromDate,
    toDate: ledgerToDate,
    status: ledgerStatus,
  }), [entries, accounts, ledgerFromDate, ledgerToDate, ledgerStatus]);

  const ledgerRows = useMemo(() => buildLedgerRows(entries, accounts, ledgerAccountKey, {
    fromDate: ledgerFromDate,
    toDate: ledgerToDate,
    status: ledgerStatus,
  }), [entries, accounts, ledgerAccountKey, ledgerFromDate, ledgerToDate, ledgerStatus]);

  const filteredLedgerRows = useMemo(() => ledgerRows.filter((row) => matchesSearch([
    row.entryId,
    row.description,
    row.referenceType,
    row.referenceId,
  ].join(' '), ledgerSearch)), [ledgerRows, ledgerSearch]);

  const balanceSheet = useMemo(() => buildBalanceSheetData(entries, accounts, {
    toDate: balanceSheetDate,
    status: balanceSheetStatus,
  }), [entries, accounts, balanceSheetDate, balanceSheetStatus]);

  const filterStatementRows = <T extends { accountCode: string; accountName: string }>(rows: T[]) => rows.filter((row) => matchesSearch(`${row.accountCode} ${row.accountName}`, balanceSheetSearch));
  const filteredAssets = useMemo(() => filterStatementRows(balanceSheet.assets), [balanceSheet.assets, balanceSheetSearch]);
  const filteredLiabilities = useMemo(() => filterStatementRows(balanceSheet.liabilities), [balanceSheet.liabilities, balanceSheetSearch]);
  const filteredEquity = useMemo(() => filterStatementRows(balanceSheet.equity), [balanceSheet.equity, balanceSheetSearch]);

  const incomeStatement = useMemo(() => buildIncomeStatementData(entries, accounts, {
    fromDate: incomeFromDate,
    toDate: incomeToDate,
    status: incomeStatus,
  }), [entries, accounts, incomeFromDate, incomeToDate, incomeStatus]);

  const filteredRevenueRows = useMemo(() => incomeStatement.revenues.filter((row) => matchesSearch(`${row.accountCode} ${row.accountName}`, incomeSearch)), [incomeStatement.revenues, incomeSearch]);
  const filteredExpenseRows = useMemo(() => incomeStatement.expenses.filter((row) => matchesSearch(`${row.accountCode} ${row.accountName}`, incomeSearch)), [incomeStatement.expenses, incomeSearch]);
  const filteredRevenueTotal = useMemo(() => filteredRevenueRows.reduce((sum, row) => sum + row.amount, 0), [filteredRevenueRows]);
  const filteredExpenseTotal = useMemo(() => filteredExpenseRows.reduce((sum, row) => sum + row.amount, 0), [filteredExpenseRows]);

  const cashRowsBase = useMemo(() => buildCashBankRows(entries, accounts, {
    fromDate: cashFromDate,
    toDate: cashToDate,
    status: cashStatus,
  }), [entries, accounts, cashFromDate, cashToDate, cashStatus]);

  const cashAccountOptions = useMemo(() => {
    const unique = new Map<string, { key: string; label: string }>();
    cashRowsBase.forEach((row) => {
      const key = `${row.accountCode}::${row.accountName}`;
      if (!unique.has(key)) {
        unique.set(key, { key, label: `${row.accountCode} - ${row.accountName}` });
      }
    });
    return Array.from(unique.values()).sort((left, right) => left.label.localeCompare(right.label, 'ar'));
  }, [cashRowsBase]);

  const filteredCashRows = useMemo(() => cashRowsBase.filter((row) => {
    const matchesAccount = cashAccountKey === 'all' || `${row.accountCode}::${row.accountName}` === cashAccountKey;
    const matchesText = matchesSearch([
      row.accountCode,
      row.accountName,
      row.description,
      row.referenceType,
      row.referenceId,
      row.counterparty,
    ].join(' '), cashSearch);
    return matchesAccount && matchesText;
  }), [cashRowsBase, cashAccountKey, cashSearch]);

  const cashTotals = useMemo(() => ({
    debit: filteredCashRows.reduce((sum, row) => sum + row.debit, 0),
    credit: filteredCashRows.reduce((sum, row) => sum + row.credit, 0),
    movement: filteredCashRows.reduce((sum, row) => sum + row.movement, 0),
  }), [filteredCashRows]);

  const cashFlowRowsBase = useMemo(() => buildCashFlowRows(entries, accounts, {
    fromDate: flowFromDate,
    toDate: flowToDate,
    status: flowStatus,
  }), [entries, accounts, flowFromDate, flowToDate, flowStatus]);

  const filteredCashFlowRows = useMemo(() => cashFlowRowsBase.filter((row) => {
    const matchesCategory = flowCategory === 'all' || row.category === flowCategory;
    const matchesText = matchesSearch([
      row.description,
      row.referenceType,
      row.referenceId,
      row.category,
    ].join(' '), flowSearch);
    return matchesCategory && matchesText;
  }), [cashFlowRowsBase, flowCategory, flowSearch]);

  const cashFlowTotals = useMemo(() => ({
    inflow: filteredCashFlowRows.reduce((sum, row) => sum + row.inflow, 0),
    outflow: filteredCashFlowRows.reduce((sum, row) => sum + row.outflow, 0),
    net: filteredCashFlowRows.reduce((sum, row) => sum + row.net, 0),
  }), [filteredCashFlowRows]);

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>التقارير المالية</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-muted-foreground">
            جميع هذه التقارير تعتمد على القيود المحاسبية فقط، وليس على الفواتير أو السندات بشكل مباشر.
          </p>
        </CardContent>
      </Card>

      <Tabs defaultValue="trial-balance" className="space-y-4">
        <TabsList className="h-auto w-full flex-wrap justify-start gap-1 bg-muted p-1">
          <TabsTrigger value="trial-balance">ميزان المراجعة</TabsTrigger>
          <TabsTrigger value="general-ledger">دفتر الأستاذ</TabsTrigger>
          <TabsTrigger value="balance-sheet">الميزانية العمومية</TabsTrigger>
          <TabsTrigger value="income-statement">قائمة الدخل</TabsTrigger>
          <TabsTrigger value="cash-bank">الصندوق / البنك</TabsTrigger>
          <TabsTrigger value="cash-flow">التدفقات النقدية</TabsTrigger>
        </TabsList>

        <TabsContent value="trial-balance" className="space-y-4">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-3 md:grid-cols-5">
                <Input type="date" value={trialFromDate} onChange={(event) => setTrialFromDate(event.target.value)} />
                <Input type="date" value={trialToDate} onChange={(event) => setTrialToDate(event.target.value)} />
                <Select value={trialStatus} onValueChange={(value) => setTrialStatus(value as FinancialEntryStatus)}>
                  <SelectTrigger><SelectValue placeholder="حالة القيد" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">كل القيود</SelectItem>
                    <SelectItem value="posted">القيود المرحلة فقط</SelectItem>
                    <SelectItem value="draft">القيود المسودة فقط</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={trialCategory} onValueChange={(value) => setTrialCategory(value as typeof trialCategory)}>
                  <SelectTrigger><SelectValue placeholder="التصنيف" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">كل التصنيفات</SelectItem>
                    <SelectItem value="assets">الأصول</SelectItem>
                    <SelectItem value="liabilities">الالتزامات</SelectItem>
                    <SelectItem value="equity">حقوق الملكية</SelectItem>
                    <SelectItem value="revenues">الإيرادات</SelectItem>
                    <SelectItem value="expenses">المصروفات</SelectItem>
                  </SelectContent>
                </Select>
                <Input value={trialSearch} onChange={(event) => setTrialSearch(event.target.value)} placeholder="بحث بالحساب أو الاسم" />
              </div>

              <div className="grid gap-4 md:grid-cols-4">
                <ReportStat label="عدد الحسابات" value={filteredTrialRows.length} />
                <ReportStat label="إجمالي المدين" value={fmt(trialTotals.debitTotal)} className="text-emerald-700" />
                <ReportStat label="إجمالي الدائن" value={fmt(trialTotals.creditTotal)} className="text-rose-700" />
                <ReportStat label="فرق التوازن" value={fmt(Math.abs(trialTotals.debitTotal - trialTotals.creditTotal))} className={Math.abs(trialTotals.debitTotal - trialTotals.creditTotal) < 0.0001 ? 'text-emerald-700' : 'text-amber-700'} />
              </div>

              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>رمز الحساب</TableHead>
                      <TableHead>اسم الحساب</TableHead>
                      <TableHead>التصنيف</TableHead>
                      <TableHead className="text-right">إجمالي المدين</TableHead>
                      <TableHead className="text-right">إجمالي الدائن</TableHead>
                      <TableHead className="text-right">رصيد مدين</TableHead>
                      <TableHead className="text-right">رصيد دائن</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredTrialRows.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} className="py-8 text-center text-muted-foreground">لا توجد بيانات ضمن الفلاتر الحالية.</TableCell>
                      </TableRow>
                    ) : filteredTrialRows.map((row) => (
                      <TableRow key={row.key}>
                        <TableCell>{row.accountCode}</TableCell>
                        <TableCell className="font-medium">{row.accountName}</TableCell>
                        <TableCell>{row.category}</TableCell>
                        <TableCell className="text-right">{fmt(row.debitTotal)}</TableCell>
                        <TableCell className="text-right">{fmt(row.creditTotal)}</TableCell>
                        <TableCell className="text-right text-emerald-700">{row.balanceDebit ? fmt(row.balanceDebit) : '-'}</TableCell>
                        <TableCell className="text-right text-rose-700">{row.balanceCredit ? fmt(row.balanceCredit) : '-'}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="general-ledger" className="space-y-4">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-3 md:grid-cols-5">
                <Input type="date" value={ledgerFromDate} onChange={(event) => setLedgerFromDate(event.target.value)} />
                <Input type="date" value={ledgerToDate} onChange={(event) => setLedgerToDate(event.target.value)} />
                <Select value={ledgerStatus} onValueChange={(value) => setLedgerStatus(value as FinancialEntryStatus)}>
                  <SelectTrigger><SelectValue placeholder="حالة القيد" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">كل القيود</SelectItem>
                    <SelectItem value="posted">القيود المرحلة فقط</SelectItem>
                    <SelectItem value="draft">القيود المسودة فقط</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={ledgerAccountKey || 'all'} onValueChange={(value) => setLedgerAccountKey(value === 'all' ? '' : value)}>
                  <SelectTrigger><SelectValue placeholder="اختر الحساب" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">اختر الحساب</SelectItem>
                    {ledgerAccountOptions.map((row) => (
                      <SelectItem key={row.key} value={row.key}>{`${row.accountCode} - ${row.accountName}`}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Input value={ledgerSearch} onChange={(event) => setLedgerSearch(event.target.value)} placeholder="بحث بالوصف أو المرجع" />
              </div>

              {!ledgerAccountKey ? (
                <div className="rounded-md border border-dashed p-8 text-center text-muted-foreground">اختر حسابًا لعرض دفتر الأستاذ العام.</div>
              ) : (
                <>
                  <div className="grid gap-4 md:grid-cols-4">
                    <ReportStat label="عدد السطور" value={filteredLedgerRows.length} />
                    <ReportStat label="إجمالي المدين" value={fmt(filteredLedgerRows.reduce((sum, row) => sum + row.debit, 0))} className="text-emerald-700" />
                    <ReportStat label="إجمالي الدائن" value={fmt(filteredLedgerRows.reduce((sum, row) => sum + row.credit, 0))} className="text-rose-700" />
                    <ReportStat label="الرصيد التراكمي الأخير" value={fmt((filteredLedgerRows.at(-1)?.runningDebit || 0) + (filteredLedgerRows.at(-1)?.runningCredit || 0))} />
                  </div>

                  <div className="overflow-x-auto rounded-md border">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>رقم القيد</TableHead>
                          <TableHead>التاريخ</TableHead>
                          <TableHead>البيان</TableHead>
                          <TableHead>المرجع</TableHead>
                          <TableHead className="text-right">مدين</TableHead>
                          <TableHead className="text-right">دائن</TableHead>
                          <TableHead className="text-right">رصيد مدين</TableHead>
                          <TableHead className="text-right">رصيد دائن</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {filteredLedgerRows.length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={8} className="py-8 text-center text-muted-foreground">لا توجد حركات دفتر أستاذ مطابقة.</TableCell>
                          </TableRow>
                        ) : filteredLedgerRows.map((row) => (
                          <TableRow key={`${row.entryId}-${row.date}-${row.referenceId}-${row.debit}-${row.credit}`}>
                            <TableCell>{row.entryId}</TableCell>
                            <TableCell>{row.date}</TableCell>
                            <TableCell className="max-w-[320px] whitespace-normal">{row.description || '-'}</TableCell>
                            <TableCell>{row.referenceType} / {row.referenceId}</TableCell>
                            <TableCell className="text-right">{row.debit ? fmt(row.debit) : '-'}</TableCell>
                            <TableCell className="text-right">{row.credit ? fmt(row.credit) : '-'}</TableCell>
                            <TableCell className="text-right text-emerald-700">{row.runningDebit ? fmt(row.runningDebit) : '-'}</TableCell>
                            <TableCell className="text-right text-rose-700">{row.runningCredit ? fmt(row.runningCredit) : '-'}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="balance-sheet" className="space-y-4">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-3 md:grid-cols-3">
                <Input type="date" value={balanceSheetDate} onChange={(event) => setBalanceSheetDate(event.target.value)} />
                <Select value={balanceSheetStatus} onValueChange={(value) => setBalanceSheetStatus(value as FinancialEntryStatus)}>
                  <SelectTrigger><SelectValue placeholder="حالة القيد" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">كل القيود</SelectItem>
                    <SelectItem value="posted">القيود المرحلة فقط</SelectItem>
                    <SelectItem value="draft">القيود المسودة فقط</SelectItem>
                  </SelectContent>
                </Select>
                <Input value={balanceSheetSearch} onChange={(event) => setBalanceSheetSearch(event.target.value)} placeholder="بحث بالحساب" />
              </div>

              <div className="grid gap-4 md:grid-cols-4">
                <ReportStat label="إجمالي الأصول" value={fmt(filteredAssets.reduce((sum, row) => sum + row.amount, 0))} className="text-emerald-700" />
                <ReportStat label="إجمالي الالتزامات" value={fmt(filteredLiabilities.reduce((sum, row) => sum + row.amount, 0))} className="text-rose-700" />
                <ReportStat label="إجمالي حقوق الملكية" value={fmt(filteredEquity.reduce((sum, row) => sum + row.amount, 0))} className="text-sky-700" />
                <ReportStat label="فرق المعادلة" value={fmt(Math.abs(filteredAssets.reduce((sum, row) => sum + row.amount, 0) - (filteredLiabilities.reduce((sum, row) => sum + row.amount, 0) + filteredEquity.reduce((sum, row) => sum + row.amount, 0))))} className={Math.abs(balanceSheet.difference) < 0.0001 ? 'text-emerald-700' : 'text-amber-700'} />
              </div>

              <div className="grid gap-4 xl:grid-cols-3">
                {[
                  { title: 'الأصول', rows: filteredAssets },
                  { title: 'الالتزامات', rows: filteredLiabilities },
                  { title: 'حقوق الملكية', rows: filteredEquity },
                ].map((section) => (
                  <Card key={section.title}>
                    <CardHeader><CardTitle className="text-base">{section.title}</CardTitle></CardHeader>
                    <CardContent>
                      <div className="overflow-x-auto rounded-md border">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>الحساب</TableHead>
                              <TableHead className="text-right">القيمة</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {section.rows.length === 0 ? (
                              <TableRow>
                                <TableCell colSpan={2} className="py-6 text-center text-muted-foreground">لا توجد أرصدة مطابقة.</TableCell>
                              </TableRow>
                            ) : section.rows.map((row) => (
                              <TableRow key={row.key}>
                                <TableCell>{row.accountCode} - {row.accountName}</TableCell>
                                <TableCell className="text-right">{fmt(row.amount)}</TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="income-statement" className="space-y-4">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-3 md:grid-cols-4">
                <Input type="date" value={incomeFromDate} onChange={(event) => setIncomeFromDate(event.target.value)} />
                <Input type="date" value={incomeToDate} onChange={(event) => setIncomeToDate(event.target.value)} />
                <Select value={incomeStatus} onValueChange={(value) => setIncomeStatus(value as FinancialEntryStatus)}>
                  <SelectTrigger><SelectValue placeholder="حالة القيد" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">كل القيود</SelectItem>
                    <SelectItem value="posted">القيود المرحلة فقط</SelectItem>
                    <SelectItem value="draft">القيود المسودة فقط</SelectItem>
                  </SelectContent>
                </Select>
                <Input value={incomeSearch} onChange={(event) => setIncomeSearch(event.target.value)} placeholder="بحث بالحساب" />
              </div>

              <div className="grid gap-4 md:grid-cols-3">
                <ReportStat label="إجمالي الإيرادات" value={fmt(filteredRevenueTotal)} className="text-emerald-700" />
                <ReportStat label="إجمالي المصروفات" value={fmt(filteredExpenseTotal)} className="text-rose-700" />
                <ReportStat label="صافي الربح / الخسارة" value={fmt(Math.abs(filteredRevenueTotal - filteredExpenseTotal))} className={filteredRevenueTotal - filteredExpenseTotal >= 0 ? 'text-emerald-700' : 'text-rose-700'} />
              </div>

              <div className="grid gap-4 xl:grid-cols-2">
                {[
                  { title: 'الإيرادات', rows: filteredRevenueRows },
                  { title: 'المصروفات', rows: filteredExpenseRows },
                ].map((section) => (
                  <Card key={section.title}>
                    <CardHeader><CardTitle className="text-base">{section.title}</CardTitle></CardHeader>
                    <CardContent>
                      <div className="overflow-x-auto rounded-md border">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>الحساب</TableHead>
                              <TableHead className="text-right">القيمة</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {section.rows.length === 0 ? (
                              <TableRow>
                                <TableCell colSpan={2} className="py-6 text-center text-muted-foreground">لا توجد أرصدة مطابقة.</TableCell>
                              </TableRow>
                            ) : section.rows.map((row) => (
                              <TableRow key={row.key}>
                                <TableCell>{row.accountCode} - {row.accountName}</TableCell>
                                <TableCell className="text-right">{fmt(row.amount)}</TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="cash-bank" className="space-y-4">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-3 md:grid-cols-5">
                <Input type="date" value={cashFromDate} onChange={(event) => setCashFromDate(event.target.value)} />
                <Input type="date" value={cashToDate} onChange={(event) => setCashToDate(event.target.value)} />
                <Select value={cashStatus} onValueChange={(value) => setCashStatus(value as FinancialEntryStatus)}>
                  <SelectTrigger><SelectValue placeholder="حالة القيد" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">كل القيود</SelectItem>
                    <SelectItem value="posted">القيود المرحلة فقط</SelectItem>
                    <SelectItem value="draft">القيود المسودة فقط</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={cashAccountKey} onValueChange={setCashAccountKey}>
                  <SelectTrigger><SelectValue placeholder="حساب الصندوق / البنك" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">كل الحسابات النقدية</SelectItem>
                    {cashAccountOptions.map((option) => (
                      <SelectItem key={option.key} value={option.key}>{option.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Input value={cashSearch} onChange={(event) => setCashSearch(event.target.value)} placeholder="بحث بالبيان أو الطرف المقابل" />
              </div>

              <div className="grid gap-4 md:grid-cols-4">
                <ReportStat label="عدد الحركات" value={filteredCashRows.length} />
                <ReportStat label="إجمالي المقبوضات" value={fmt(cashTotals.debit)} className="text-emerald-700" />
                <ReportStat label="إجمالي المدفوعات" value={fmt(cashTotals.credit)} className="text-rose-700" />
                <ReportStat label="صافي الحركة" value={fmt(Math.abs(cashTotals.movement))} className={cashTotals.movement >= 0 ? 'text-emerald-700' : 'text-rose-700'} />
              </div>

              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>التاريخ</TableHead>
                      <TableHead>الحساب</TableHead>
                      <TableHead>البيان</TableHead>
                      <TableHead>الطرف المقابل</TableHead>
                      <TableHead>المرجع</TableHead>
                      <TableHead className="text-right">مدين</TableHead>
                      <TableHead className="text-right">دائن</TableHead>
                      <TableHead className="text-right">الرصيد التراكمي</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredCashRows.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={8} className="py-8 text-center text-muted-foreground">لا توجد حركات نقدية مطابقة.</TableCell>
                      </TableRow>
                    ) : filteredCashRows.map((row) => (
                      <TableRow key={row.key}>
                        <TableCell>{row.date}</TableCell>
                        <TableCell>{row.accountCode} - {row.accountName}</TableCell>
                        <TableCell className="max-w-[260px] whitespace-normal">{row.description || '-'}</TableCell>
                        <TableCell>{row.counterparty || '-'}</TableCell>
                        <TableCell>{row.referenceType} / {row.referenceId}</TableCell>
                        <TableCell className="text-right text-emerald-700">{row.debit ? fmt(row.debit) : '-'}</TableCell>
                        <TableCell className="text-right text-rose-700">{row.credit ? fmt(row.credit) : '-'}</TableCell>
                        <TableCell className="text-right">{fmt(Math.abs(row.runningBalance))}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="cash-flow" className="space-y-4">
          <Card>
            <CardContent className="space-y-4 pt-6">
              <div className="grid gap-3 md:grid-cols-5">
                <Input type="date" value={flowFromDate} onChange={(event) => setFlowFromDate(event.target.value)} />
                <Input type="date" value={flowToDate} onChange={(event) => setFlowToDate(event.target.value)} />
                <Select value={flowStatus} onValueChange={(value) => setFlowStatus(value as FinancialEntryStatus)}>
                  <SelectTrigger><SelectValue placeholder="حالة القيد" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">كل القيود</SelectItem>
                    <SelectItem value="posted">القيود المرحلة فقط</SelectItem>
                    <SelectItem value="draft">القيود المسودة فقط</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={flowCategory} onValueChange={(value) => setFlowCategory(value as typeof flowCategory)}>
                  <SelectTrigger><SelectValue placeholder="نوع التدفق" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">كل التدفقات</SelectItem>
                    <SelectItem value="operating">تشغيلي</SelectItem>
                    <SelectItem value="investing">استثماري</SelectItem>
                    <SelectItem value="financing">تمويلي</SelectItem>
                  </SelectContent>
                </Select>
                <Input value={flowSearch} onChange={(event) => setFlowSearch(event.target.value)} placeholder="بحث بالوصف أو المرجع" />
              </div>

              <div className="grid gap-4 md:grid-cols-3">
                <ReportStat label="إجمالي الداخل النقدي" value={fmt(cashFlowTotals.inflow)} className="text-emerald-700" />
                <ReportStat label="إجمالي الخارج النقدي" value={fmt(cashFlowTotals.outflow)} className="text-rose-700" />
                <ReportStat label="صافي التدفق" value={fmt(Math.abs(cashFlowTotals.net))} className={cashFlowTotals.net >= 0 ? 'text-emerald-700' : 'text-rose-700'} />
              </div>

              <div className="rounded-md border bg-amber-50 p-3 text-xs text-amber-900">
                هذا التقرير اختياري ومتقدم، ويعتمد على تصنيف تقديري لنوع التدفق من الطرف المقابل في القيد (تشغيلي / استثماري / تمويلي).
              </div>

              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>التاريخ</TableHead>
                      <TableHead>البيان</TableHead>
                      <TableHead>نوع التدفق</TableHead>
                      <TableHead>المرجع</TableHead>
                      <TableHead className="text-right">داخل</TableHead>
                      <TableHead className="text-right">خارج</TableHead>
                      <TableHead className="text-right">الصافي</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredCashFlowRows.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} className="py-8 text-center text-muted-foreground">لا توجد تدفقات نقدية مطابقة.</TableCell>
                      </TableRow>
                    ) : filteredCashFlowRows.map((row) => (
                      <TableRow key={row.key}>
                        <TableCell>{row.date}</TableCell>
                        <TableCell className="max-w-[320px] whitespace-normal">{row.description || '-'}</TableCell>
                        <TableCell>{row.category === 'operating' ? 'تشغيلي' : row.category === 'investing' ? 'استثماري' : 'تمويلي'}</TableCell>
                        <TableCell>{row.referenceType} / {row.referenceId}</TableCell>
                        <TableCell className="text-right text-emerald-700">{row.inflow ? fmt(row.inflow) : '-'}</TableCell>
                        <TableCell className="text-right text-rose-700">{row.outflow ? fmt(row.outflow) : '-'}</TableCell>
                        <TableCell className="text-right">{fmt(Math.abs(row.net))}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
