'use client';

import { useCallback, useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { useToast } from '@/hooks/use-toast';
import type { BankReconciliationPeriod, BankTransaction, LedgerTransaction, ReconciliationMatch, BankReconciliationDifference } from '@/lib/types';
import type { ReconciliationSummary } from '@/app/api/admin/bank-reconciliation/periods/[id]/summary/route';

/* ─── helpers ────────────────────────────────────────────────────────────── */

function fmt(n: number) {
  return n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function dirLabel(dir?: string) {
  if (dir === 'inward' || dir === 'debit') return { label: 'وارد', cls: 'text-green-700 bg-green-50' };
  return { label: 'صادر', cls: 'text-red-700 bg-red-50' };
}

const DIFF_TYPE_LABELS: Record<string, string> = {
  unmatched_bank_transaction: 'حركة بنكية بلا قيد',
  unmatched_ledger_transaction: 'قيد بلا حركة بنكية',
  outstanding_check: 'شيك لم يُصرف',
  deposit_in_transit: 'إيداع في الطريق',
  bank_fee: 'رسوم بنكية',
  amount_mismatch: 'فرق مبلغ',
  date_variance: 'فرق تاريخ',
  forex_difference: 'فرق عملة',
  other: 'أخرى',
};

const STATUS_COLORS: Record<string, string> = {
  draft: 'bg-gray-100 text-gray-700',
  'in-progress': 'bg-blue-100 text-blue-700',
  completed: 'bg-green-100 text-green-700',
  locked: 'bg-amber-100 text-amber-800',
};

/* ─── Balance Summary Panel ──────────────────────────────────────────────── */

function BalanceSummaryPanel({ summary, period }: { summary: ReconciliationSummary; period: BankReconciliationPeriod }) {
  const diffOk = Math.abs(summary.difference) < 0.01;

  return (
    <div className="rounded-xl border bg-card shadow-sm overflow-hidden">
      <div className="border-b px-6 py-4 flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold">ملخص التسوية</h2>
          <p className="text-xs text-muted-foreground mt-0.5">
            {period.periodStartDate} → {period.periodEndDate}
          </p>
        </div>
        <div className="flex items-center gap-3">
          <span className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold ${STATUS_COLORS[period.status] || 'bg-gray-100 text-gray-700'}`}>
            {period.status === 'draft' ? 'مسودة'
              : period.status === 'in-progress' ? 'جارٍ العمل'
              : period.status === 'completed' ? 'مكتملة'
              : 'مقفلة'}
          </span>
          <span className={`text-sm font-bold ${summary.matchRate >= 80 ? 'text-green-600' : summary.matchRate >= 50 ? 'text-amber-600' : 'text-red-600'}`}>
            نسبة المطابقة: {summary.matchRate}%
          </span>
        </div>
      </div>

      <div className="grid grid-cols-2 divide-x rtl:divide-x-reverse">
        {/* Bank Statement Side */}
        <div className="p-5 space-y-3">
          <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">كشف البنك</p>
          <SummaryRow label="رصيد البداية" value={summary.statementOpeningBalance} />
          <SummaryRow label="+ إيداعات في الطريق" value={summary.depositsInTransit} positive />
          <SummaryRow label="- شيكات معلقة" value={summary.outstandingChecks} negative />
          <div className="border-t pt-3">
            <SummaryRow label="الرصيد المعدّل (بنك)" value={summary.adjustedBankBalance} bold />
          </div>
        </div>

        {/* Book Side */}
        <div className="p-5 space-y-3">
          <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">الدفاتر المحاسبية</p>
          <SummaryRow label="رصيد الختام (كشف)" value={summary.statementClosingBalance} />
          <SummaryRow label="+ قيود غير موجودة بالبنك (وارد)" value={summary.unmatchedBankInflows} positive />
          <SummaryRow label="- رسوم غير مسجلة بالدفاتر" value={summary.unmatchedBankOutflows} negative />
          <div className="border-t pt-3">
            <SummaryRow label="الرصيد المعدّل (دفاتر)" value={summary.adjustedBookBalance} bold />
          </div>
        </div>
      </div>

      {/* Difference */}
      <div className={`px-6 py-4 border-t flex items-center justify-between ${diffOk ? 'bg-green-50' : 'bg-red-50'}`}>
        <div className="flex items-center gap-3">
          <div className={`w-3 h-3 rounded-full ${diffOk ? 'bg-green-500' : 'bg-red-500'}`} />
          <span className="font-semibold text-sm">
            {diffOk ? 'التسوية مكتملة — الأرصدة متطابقة' : 'يوجد فرق — يتطلب مراجعة'}
          </span>
        </div>
        <span className={`text-xl font-bold ${diffOk ? 'text-green-700' : 'text-red-700'}`}>
          {fmt(summary.difference)}
        </span>
      </div>

      {/* Counts */}
      <div className="px-6 py-3 bg-muted/30 flex flex-wrap gap-4 text-xs text-muted-foreground border-t">
        <span>حركات البنك: <strong className="text-foreground">{summary.totalBankTransactions}</strong></span>
        <span>مطابق: <strong className="text-green-600">{summary.matchedBankTransactions}</strong></span>
        <span>غير مطابق: <strong className="text-red-600">{summary.unmatchedBankTransactions}</strong></span>
        <span className="mx-2 text-border">|</span>
        <span>قيود الدفتر: <strong className="text-foreground">{summary.totalLedgerTransactions}</strong></span>
        <span>مطابق: <strong className="text-green-600">{summary.matchedLedgerTransactions}</strong></span>
        <span>غير مطابق: <strong className="text-red-600">{summary.unmatchedLedgerTransactions}</strong></span>
      </div>
    </div>
  );
}

function SummaryRow({ label, value, positive, negative, bold }: {
  label: string; value: number; positive?: boolean; negative?: boolean; bold?: boolean;
}) {
  return (
    <div className={`flex justify-between items-center text-sm ${bold ? 'font-semibold' : ''}`}>
      <span className="text-muted-foreground">{label}</span>
      <span className={positive ? 'text-green-600' : negative ? 'text-red-600' : ''} dir="ltr">
        {positive ? '+' : negative ? '-' : ''}{fmt(value)}
      </span>
    </div>
  );
}

/* ─── Main Workspace Component ───────────────────────────────────────────── */

export function BankReconciliationWorkspace({
  period,
  matchedBy,
  onPeriodUpdated,
}: {
  period: BankReconciliationPeriod;
  matchedBy: string;
  onPeriodUpdated: (p: BankReconciliationPeriod) => void;
}) {
  const { toast } = useToast();

  const [summary, setSummary] = useState<ReconciliationSummary | null>(null);
  const [bankTransactions, setBankTransactions] = useState<BankTransaction[]>([]);
  const [ledgerTransactions, setLedgerTransactions] = useState<LedgerTransaction[]>([]);
  const [matches, setMatches] = useState<ReconciliationMatch[]>([]);
  const [differences, setDifferences] = useState<BankReconciliationDifference[]>([]);
  const [loading, setLoading] = useState(false);

  // Selection for manual match
  const [selectedBankId, setSelectedBankId] = useState<string | null>(null);
  const [selectedLedgerIds, setSelectedLedgerIds] = useState<string[]>([]);

  // Auto-match threshold
  const [threshold, setThreshold] = useState(80);
  const [autoMatchLoading, setAutoMatchLoading] = useState(false);

  const periodId = period.id;
  const isLocked = period.status === 'locked';

  /* ─ data fetching ─ */

  const loadAll = useCallback(async () => {
    setLoading(true);
    try {
      const [summaryRes, bankRes, matchRes, diffRes] = await Promise.all([
        fetch(`/api/admin/bank-reconciliation/periods/${periodId}/summary`),
        fetch(`/api/admin/bank-reconciliation/periods/${periodId}/bank-transactions`),
        fetch(`/api/admin/bank-reconciliation/periods/${periodId}/reconciliation-matches`),
        fetch(`/api/admin/bank-reconciliation/differences?periodId=${periodId}`),
      ]);

      if (summaryRes.ok) setSummary(await summaryRes.json());

      // Bank transactions — use the import route data or fallback API
      if (bankRes.ok) {
        const data = await bankRes.json();
        setBankTransactions(Array.isArray(data) ? data : data.items || []);
      }

      if (matchRes.ok) {
        const data = await matchRes.json();
        setMatches(Array.isArray(data) ? data : data.items || []);
      }

      if (diffRes.ok) {
        const data = await diffRes.json();
        setDifferences(Array.isArray(data) ? data : data.items || []);
      }
    } catch (err) {
      toast({ title: 'خطأ', description: 'تعذر تحميل بيانات التسوية', variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  }, [periodId]);

  // Also load ledger separately
  const loadLedger = useCallback(async () => {
    try {
      const res = await fetch(`/api/admin/bank-reconciliation/periods/${periodId}/ledger-transactions`);
      if (res.ok) {
        const data = await res.json();
        setLedgerTransactions(Array.isArray(data) ? data : data.items || []);
      }
    } catch {
      // silent — ledger may not be populated yet
    }
  }, [periodId]);

  useEffect(() => {
    void loadAll();
    void loadLedger();
  }, [loadAll, loadLedger]);

  /* ─ derived state ─ */

  const matchedBankIds = new Set(matches.map((m) => m.bankTransactionId));
  const matchedLedgerIds = new Set(matches.flatMap((m) => m.ledgerTransactionIds));
  const bankMatchMap = new Map(matches.map((m) => [m.bankTransactionId, m]));

  /* ─ actions ─ */

  const runAutoMatch = async (dryRun: boolean) => {
    setAutoMatchLoading(true);
    try {
      const res = await fetch(
        `/api/admin/bank-reconciliation/periods/${periodId}/auto-match/${dryRun ? 'preview' : 'apply'}`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            threshold,
            matchedBy: matchedBy || 'system',
            applyFromPreview: !dryRun,
            dryRun,
          }),
        }
      );
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(String(err?.error || 'فشلت المطابقة'));
      }
      const result = await res.json();
      const count = dryRun ? result.suggestions?.length ?? 0 : result.appliedCount ?? 0;
      toast({
        title: dryRun ? 'معاينة المطابقة' : 'تمت المطابقة',
        description: `${count} ${dryRun ? 'اقتراح' : 'مطابقة مطبقة'}`,
      });
      if (!dryRun) await loadAll();
    } catch (err) {
      toast({ title: 'خطأ', description: err instanceof Error ? err.message : 'خطأ', variant: 'destructive' });
    } finally {
      setAutoMatchLoading(false);
    }
  };

  const createManualMatch = async () => {
    if (!selectedBankId || selectedLedgerIds.length === 0) return;
    try {
      const res = await fetch(`/api/admin/bank-reconciliation/periods/${periodId}/manual-match`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          bankTransactionId: selectedBankId,
          ledgerTransactionIds: selectedLedgerIds,
          matchedBy: matchedBy || 'system',
        }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(String(err?.error || 'فشلت المطابقة اليدوية'));
      }
      toast({ title: 'نجاح', description: 'تمت المطابقة اليدوية' });
      setSelectedBankId(null);
      setSelectedLedgerIds([]);
      await loadAll();
      await loadLedger();
    } catch (err) {
      toast({ title: 'خطأ', description: err instanceof Error ? err.message : 'خطأ', variant: 'destructive' });
    }
  };

  const unmatchTransaction = async (matchId: string) => {
    try {
      const res = await fetch(
        `/api/admin/bank-reconciliation/periods/${periodId}/matches/${matchId}`,
        { method: 'DELETE' }
      );
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(String(err?.error || 'فشل إلغاء المطابقة'));
      }
      toast({ title: 'نجاح', description: 'تم إلغاء المطابقة' });
      await loadAll();
      await loadLedger();
    } catch (err) {
      toast({ title: 'خطأ', description: err instanceof Error ? err.message : 'خطأ', variant: 'destructive' });
    }
  };

  const handleLock = async (action: 'lock' | 'complete' | 'reopen') => {
    try {
      const res = await fetch(`/api/admin/bank-reconciliation/periods/${periodId}/lock`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action, actorId: matchedBy || 'system' }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(String(err?.error || 'فشل تغيير الحالة'));
      }
      const updated = await res.json();
      toast({
        title: 'نجاح',
        description: action === 'lock' ? 'تم قفل الفترة' : action === 'complete' ? 'تم اعتماد التسوية' : 'تم إعادة فتح الفترة',
      });
      onPeriodUpdated(updated as BankReconciliationPeriod);
      await loadAll();
    } catch (err) {
      toast({ title: 'خطأ', description: err instanceof Error ? err.message : 'خطأ', variant: 'destructive' });
    }
  };

  const toggleLedgerSelection = (id: string) => {
    setSelectedLedgerIds((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
    );
  };

  /* ─ render ─ */

  if (loading && !summary) {
    return (
      <div className="flex items-center justify-center py-16 text-muted-foreground text-sm">
        جارٍ تحميل بيانات التسوية...
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {/* Balance Summary */}
      {summary && <BalanceSummaryPanel summary={summary} period={period} />}

      {/* Actions Bar */}
      <div className="flex flex-wrap items-center gap-3 p-4 rounded-lg border bg-card">
        <div className="flex items-center gap-2">
          <label className="text-sm text-muted-foreground">عتبة المطابقة:</label>
          <input
            type="number"
            lang="en"
            dir="ltr"
            min={0}
            max={100}
            value={threshold}
            onChange={(e) => setThreshold(Number(e.target.value))}
            className="w-16 rounded border border-input bg-background px-2 py-1 text-sm"
          />
          <span className="text-xs text-muted-foreground">%</span>
        </div>
        <Button
          size="sm"
          onClick={() => runAutoMatch(false)}
          disabled={isLocked || autoMatchLoading}
        >
          {autoMatchLoading ? 'جارٍ...' : 'مطابقة تلقائية'}
        </Button>
        <Button
          size="sm"
          variant="outline"
          onClick={() => runAutoMatch(true)}
          disabled={autoMatchLoading}
        >
          معاينة بدون حفظ
        </Button>

        <div className="flex-1" />

        {period.status !== 'locked' && period.status !== 'completed' && (
          <>
            <Button
              size="sm"
              variant="outline"
              onClick={() => handleLock('complete')}
            >
              اعتماد التسوية
            </Button>
            <Button
              size="sm"
              variant="destructive"
              onClick={() => handleLock('lock')}
            >
              قفل الفترة
            </Button>
          </>
        )}
        {(period.status === 'locked' || period.status === 'completed') && (
          <Button
            size="sm"
            variant="outline"
            onClick={() => handleLock('reopen')}
          >
            إعادة فتح الفترة
          </Button>
        )}
        <Button size="sm" variant="ghost" onClick={() => { void loadAll(); void loadLedger(); }}>
          تحديث
        </Button>
      </div>

      {/* Manual Match Action */}
      {selectedBankId && selectedLedgerIds.length > 0 && !isLocked && (
        <div className="flex items-center gap-3 p-3 rounded-lg border border-primary/40 bg-primary/5 text-sm">
          <span className="font-medium text-primary">
            تطابق يدوي: حركة بنكية ←→ {selectedLedgerIds.length} قيد
          </span>
          <Button size="sm" onClick={createManualMatch}>
            تأكيد المطابقة
          </Button>
          <Button size="sm" variant="ghost" onClick={() => { setSelectedBankId(null); setSelectedLedgerIds([]); }}>
            إلغاء
          </Button>
        </div>
      )}

      {/* Split View */}
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
        {/* Bank Transactions */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center justify-between">
              <span>كشف البنك</span>
              <div className="flex gap-2 text-xs font-normal">
                <span className="text-green-600">● مطابق: {matchedBankIds.size}</span>
                <span className="text-red-600">● غير مطابق: {bankTransactions.length - matchedBankIds.size}</span>
              </div>
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {bankTransactions.length === 0 ? (
              <p className="text-center text-sm text-muted-foreground py-8">
                لا توجد حركات بنكية — استورد كشف البنك أولاً
              </p>
            ) : (
              <div className="overflow-auto max-h-[480px]">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-7"></TableHead>
                      <TableHead>التاريخ</TableHead>
                      <TableHead>المبلغ</TableHead>
                      <TableHead>الاتجاه</TableHead>
                      <TableHead>الوصف</TableHead>
                      <TableHead>الحالة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {bankTransactions.map((bt) => {
                      const isMatched = matchedBankIds.has(bt.id);
                      const isSelected = selectedBankId === bt.id;
                      const match = bankMatchMap.get(bt.id);
                      const dir = dirLabel(bt.direction);
                      return (
                        <TableRow
                          key={bt.id}
                          className={`cursor-pointer transition-colors
                            ${isSelected ? 'bg-primary/10 ring-1 ring-primary/30' : ''}
                            ${isMatched ? 'opacity-60' : 'hover:bg-muted/50'}
                          `}
                          onClick={() => {
                            if (isLocked) return;
                            if (isMatched) return;
                            setSelectedBankId(isSelected ? null : bt.id);
                          }}
                        >
                          <TableCell className="pr-2">
                            <div className={`w-2.5 h-2.5 rounded-full mx-auto ${isMatched ? 'bg-green-500' : 'bg-red-400'}`} />
                          </TableCell>
                          <TableCell className="text-xs whitespace-nowrap" dir="ltr">{bt.transactionDate}</TableCell>
                          <TableCell className="text-xs font-mono" dir="ltr">{fmt(bt.amount)}</TableCell>
                          <TableCell>
                            <span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${dir.cls}`}>
                              {dir.label}
                            </span>
                          </TableCell>
                          <TableCell className="text-xs max-w-[160px] truncate">{bt.description || '—'}</TableCell>
                          <TableCell>
                            {isMatched && match ? (
                              <div className="flex items-center gap-1">
                                <Badge variant="secondary" className="text-[10px] py-0">
                                  {match.matchType === 'auto' ? 'تلقائي' : match.matchType === 'manual' ? 'يدوي' : match.matchType === 'multi-line' ? 'متعدد' : 'جزئي'}
                                  {' '}
                                  {Math.round(match.matchConfidence)}%
                                </Badge>
                                {!isLocked && (
                                  <button
                                    className="text-[10px] text-red-500 hover:underline"
                                    onClick={(e) => { e.stopPropagation(); void unmatchTransaction(match.id); }}
                                  >
                                    إلغاء
                                  </button>
                                )}
                              </div>
                            ) : (
                              <span className="text-[10px] text-muted-foreground">غير مطابق</span>
                            )}
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Ledger Transactions */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center justify-between">
              <span>الدفاتر المحاسبية</span>
              <div className="flex gap-2 text-xs font-normal">
                <span className="text-green-600">● مطابق: {matchedLedgerIds.size}</span>
                <span className="text-red-600">● غير مطابق: {ledgerTransactions.length - matchedLedgerIds.size}</span>
              </div>
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {ledgerTransactions.length === 0 ? (
              <p className="text-center text-sm text-muted-foreground py-8">
                لا توجد قيود محاسبية مرتبطة بهذا البنك في هذه الفترة
              </p>
            ) : (
              <div className="overflow-auto max-h-[480px]">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-7"></TableHead>
                      <TableHead>التاريخ</TableHead>
                      <TableHead>المبلغ</TableHead>
                      <TableHead>الاتجاه</TableHead>
                      <TableHead>الوصف</TableHead>
                      <TableHead>الحالة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {ledgerTransactions.map((lt) => {
                      const isMatched = matchedLedgerIds.has(lt.id);
                      const isSelected = selectedLedgerIds.includes(lt.id);
                      const dir = dirLabel(lt.direction);
                      return (
                        <TableRow
                          key={lt.id}
                          className={`cursor-pointer transition-colors
                            ${isSelected ? 'bg-primary/10 ring-1 ring-primary/30' : ''}
                            ${isMatched ? 'opacity-60' : 'hover:bg-muted/50'}
                          `}
                          onClick={() => {
                            if (isLocked || isMatched) return;
                            toggleLedgerSelection(lt.id);
                          }}
                        >
                          <TableCell className="pr-2">
                            <div className={`w-2.5 h-2.5 rounded-full mx-auto ${isMatched ? 'bg-green-500' : isSelected ? 'bg-primary' : 'bg-red-400'}`} />
                          </TableCell>
                          <TableCell className="text-xs whitespace-nowrap" dir="ltr">{lt.transactionDate}</TableCell>
                          <TableCell className="text-xs font-mono" dir="ltr">{fmt(lt.amount)}</TableCell>
                          <TableCell>
                            <span className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${dir.cls}`}>
                              {dir.label}
                            </span>
                          </TableCell>
                          <TableCell className="text-xs max-w-[160px] truncate">{lt.description || '—'}</TableCell>
                          <TableCell>
                            <span className={`text-[10px] ${isMatched ? 'text-green-600' : 'text-muted-foreground'}`}>
                              {isMatched ? 'مطابق' : isSelected ? 'محدد' : 'غير مطابق'}
                            </span>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Exception Queue */}
      <ExceptionQueue differences={differences} />
    </div>
  );
}

/* ─── Exception Queue ────────────────────────────────────────────────────── */

function ExceptionQueue({ differences }: { differences: BankReconciliationDifference[] }) {
  if (differences.length === 0) return null;

  const pending = differences.filter((d) => !d.resolutionType || d.resolutionType === 'pending');
  const resolved = differences.filter((d) => d.resolutionType && d.resolutionType !== 'pending');

  return (
    <Card>
      <CardHeader className="pb-3">
        <CardTitle className="text-base flex items-center gap-2">
          قائمة الاستثناءات
          {pending.length > 0 && (
            <span className="inline-flex items-center rounded-full bg-red-100 px-2 py-0.5 text-xs font-semibold text-red-700">
              {pending.length} بحاجة للمراجعة
            </span>
          )}
        </CardTitle>
      </CardHeader>
      <CardContent>
        {pending.length > 0 && (
          <div className="mb-4">
            <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">غير محلولة</p>
            <div className="overflow-auto rounded border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>النوع</TableHead>
                    <TableHead>المبلغ</TableHead>
                    <TableHead>الوصف</TableHead>
                    <TableHead>الإجراء المقترح</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {pending.map((d) => (
                    <TableRow key={d.id}>
                      <TableCell>
                        <Badge variant="destructive" className="text-[10px]">
                          {DIFF_TYPE_LABELS[d.type] || d.type}
                        </Badge>
                      </TableCell>
                      <TableCell className="font-mono text-xs" dir="ltr">{fmt(d.amount)}</TableCell>
                      <TableCell className="text-xs">{d.description || '—'}</TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {d.type === 'bank_fee' || d.type === 'unmatched_bank_transaction'
                          ? 'أنشئ قيداً محاسبياً جديداً'
                          : d.type === 'outstanding_check'
                          ? 'انتظر مقاصة الشيك'
                          : d.type === 'deposit_in_transit'
                          ? 'انتظر ظهوره بكشف البنك'
                          : d.type === 'unmatched_ledger_transaction'
                          ? 'تحقق من القيد أو انتظر الحركة البنكية'
                          : 'مراجعة يدوية'}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>
        )}

        {resolved.length > 0 && (
          <details className="text-sm">
            <summary className="cursor-pointer text-muted-foreground text-xs">
              محلولة ({resolved.length})
            </summary>
            <div className="mt-2 overflow-auto rounded border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>النوع</TableHead>
                    <TableHead>المبلغ</TableHead>
                    <TableHead>الحل</TableHead>
                    <TableHead>الوصف</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {resolved.map((d) => (
                    <TableRow key={d.id} className="opacity-60">
                      <TableCell className="text-xs">{DIFF_TYPE_LABELS[d.type] || d.type}</TableCell>
                      <TableCell className="font-mono text-xs" dir="ltr">{fmt(d.amount)}</TableCell>
                      <TableCell>
                        <Badge variant="secondary" className="text-[10px]">{d.resolutionType}</Badge>
                      </TableCell>
                      <TableCell className="text-xs">{d.description || '—'}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </details>
        )}
      </CardContent>
    </Card>
  );
}
