'use client';

import { useEffect, useMemo, useState } from 'react';
import * as XLSX from 'xlsx';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/use-toast';
import type { Bank, BankReconciliationPeriod } from '@/lib/types';
import { BankReconciliationWorkspace } from '@/components/admin/bank-reconciliation-workspace';
import { BankStatementColumnMapper } from '@/components/admin/bank-statement-column-mapper';

type PreviewResponse = {
  periodId: string;
  totalBankTransactions: number;
  candidateLedgerTransactions: number;
  threshold: number;
  suggestions: Array<{
    bankTransactionId: string;
    ledgerTransactionId: string;
    matchType: 'auto' | 'partial';
    matchConfidence: number;
  }>;
  unmatchedBank: Array<{ type: string; amount: number; description: string }>;
  unmatchedLedger: Array<{ type: string; amount: number; description: string }>;
};

type ApplyResponse = {
  periodId: string;
  appliedCount: number;
  skippedCount: number;
  matchedCount: number;
  unmatchedBankCount: number;
  unmatchedLedgerCount: number;
  dryRun?: boolean;
  skippedReasons?: Array<{ bankTransactionId: string; ledgerTransactionId: string; reason: string }>;
};

type DraftBankTransaction = {
  transactionDate: string;
  amount: string;
  direction: 'inward' | 'outward';
  description: string;
  bankReference: string;
  type: 'transfer' | 'check' | 'fee' | 'interest' | 'charge' | 'other';
  currencyCode: string;
};

function normalizeHeader(value: string): string {
  return String(value || '')
    .trim()
    .toLowerCase()
    .replace(/\s+/g, ' ');
}

function normalizeDirectionValue(value: unknown): 'inward' | 'outward' {
  const v = String(value || '').trim().toLowerCase();
  if (v === 'outward' || v === 'out' || v === 'debit' || v === 'صادر' || v === 'مدين') {
    return 'outward';
  }
  return 'inward';
}

function toPositiveNumber(value: unknown): number {
  const parsed = Number(String(value || '').replace(/,/g, '').trim());
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
}

export function BankReconciliationManager({
  defaultMatchedBy,
}: {
  defaultMatchedBy: string;
}) {
  const { toast } = useToast();

  const [banks, setBanks] = useState<Bank[]>([]);
  const [loadingBanks, setLoadingBanks] = useState(false);

  const [bankId, setBankId] = useState('');
  const [periods, setPeriods] = useState<BankReconciliationPeriod[]>([]);
  const [loadingPeriods, setLoadingPeriods] = useState(false);
  const [selectedPeriodId, setSelectedPeriodId] = useState('');

  const [periodStartDate, setPeriodStartDate] = useState('');
  const [periodEndDate, setPeriodEndDate] = useState('');
  const [statementStartBalance, setStatementStartBalance] = useState('0');
  const [statementEndBalance, setStatementEndBalance] = useState('0');

  const [importPayload, setImportPayload] = useState(
    '[]'
  );
  const [draftTxn, setDraftTxn] = useState<DraftBankTransaction>({
    transactionDate: '',
    amount: '',
    direction: 'inward',
    description: '',
    bankReference: '',
    type: 'transfer',
    currencyCode: 'USD',
  });
  const [stagedTransactions, setStagedTransactions] = useState<Array<Record<string, unknown>>>([]);
  const [importFileName, setImportFileName] = useState('');

  const [threshold, setThreshold] = useState('80');
  const [matchedBy, setMatchedBy] = useState(defaultMatchedBy);
  const [previewResult, setPreviewResult] = useState<PreviewResponse | null>(null);
  const [applyResult, setApplyResult] = useState<ApplyResponse | null>(null);

  const selectedPeriod = useMemo(
    () => periods.find((p) => p.id === selectedPeriodId) || null,
    [periods, selectedPeriodId]
  );

  const fetchBanks = async () => {
    setLoadingBanks(true);
    try {
      const response = await fetch('/api/banks');
      if (!response.ok) throw new Error('Failed to fetch banks');
      const data = (await response.json()) as Bank[];
      setBanks(data || []);
      if (!bankId && data?.length) {
        setBankId(data[0].id);
      }
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'تعذر جلب البنوك',
        variant: 'destructive',
      });
    } finally {
      setLoadingBanks(false);
    }
  };

  const fetchPeriods = async (targetBankId: string) => {
    if (!targetBankId) {
      setPeriods([]);
      setSelectedPeriodId('');
      return;
    }

    setLoadingPeriods(true);
    try {
      const response = await fetch(
        `/api/admin/bank-reconciliation/periods?bankAccountId=${encodeURIComponent(targetBankId)}&page=1&pageSize=100`
      );
      if (!response.ok) throw new Error('Failed to fetch periods');
      const data = await response.json();
      const items = (data?.items || []) as BankReconciliationPeriod[];
      setPeriods(items);
      if (!selectedPeriodId && items.length > 0) {
        setSelectedPeriodId(items[0].id);
      }
      if (selectedPeriodId && !items.some((p) => p.id === selectedPeriodId)) {
        setSelectedPeriodId(items[0]?.id || '');
      }
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'تعذر جلب فترات التسوية',
        variant: 'destructive',
      });
    } finally {
      setLoadingPeriods(false);
    }
  };

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

  useEffect(() => {
    void fetchPeriods(bankId);
  }, [bankId]);

  const createPeriod = async () => {
    if (!bankId || !periodStartDate || !periodEndDate) {
      toast({ title: 'تنبيه', description: 'يرجى اختيار البنك وإدخال تاريخ البداية والنهاية', variant: 'destructive' });
      return;
    }

    const response = await fetch('/api/admin/bank-reconciliation/periods', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        bankAccountId: bankId,
        periodStartDate,
        periodEndDate,
        statementStartBalance: Number(statementStartBalance || 0),
        statementEndBalance: Number(statementEndBalance || 0),
        createdBy: matchedBy || 'system',
      }),
    });

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      toast({ title: 'خطأ', description: String(err?.error || 'تعذر إنشاء الفترة'), variant: 'destructive' });
      return;
    }

    const created = (await response.json()) as BankReconciliationPeriod;
    toast({ title: 'نجاح', description: 'تم إنشاء فترة التسوية' });
    setPeriods((prev) => [created, ...prev]);
    setSelectedPeriodId(created.id);
  };

  const importStatement = async () => {
    if (!selectedPeriodId) {
      toast({ title: 'تنبيه', description: 'يرجى اختيار فترة أولاً', variant: 'destructive' });
      return;
    }

    let transactions: unknown[] = [];

    if (stagedTransactions.length > 0) {
      transactions = stagedTransactions;
    } else {
      let parsed: unknown;
      try {
        parsed = JSON.parse(importPayload);
      } catch {
        toast({ title: 'خطأ', description: 'صيغة JSON غير صحيحة', variant: 'destructive' });
        return;
      }

      transactions = Array.isArray(parsed)
        ? parsed
        : (parsed as { transactions?: unknown[] })?.transactions || [];
    }

    if (!transactions.length) {
      toast({ title: 'خطأ', description: 'أضف حركات أولاً (يدويًا أو عبر JSON)', variant: 'destructive' });
      return;
    }

    const response = await fetch(`/api/admin/bank-reconciliation/periods/${encodeURIComponent(selectedPeriodId)}/import`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ transactions }),
    });

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      toast({ title: 'خطأ', description: String(err?.error || 'تعذر استيراد كشف البنك'), variant: 'destructive' });
      return;
    }

    const result = await response.json();
    toast({ title: 'نجاح', description: `تم استيراد ${result?.importedCount || 0} حركة` });
    setStagedTransactions([]);
    setImportPayload('[]');
  };

  const addStagedTransaction = () => {
    const amount = Number(draftTxn.amount);
    if (!draftTxn.transactionDate || !Number.isFinite(amount) || amount <= 0) {
      toast({ title: 'تنبيه', description: 'أدخل تاريخًا صحيحًا ومبلغًا أكبر من صفر', variant: 'destructive' });
      return;
    }

    setStagedTransactions((prev) => [
      ...prev,
      {
        transactionDate: draftTxn.transactionDate,
        amount,
        direction: draftTxn.direction,
        description: draftTxn.description || null,
        bankReference: draftTxn.bankReference || null,
        type: draftTxn.type,
        currencyCode: draftTxn.currencyCode || null,
      },
    ]);

    setDraftTxn((prev) => ({
      ...prev,
      amount: '',
      description: '',
      bankReference: '',
    }));
  };

  const removeStagedTransaction = (index: number) => {
    setStagedTransactions((prev) => prev.filter((_, i) => i !== index));
  };

  const handleImportFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    try {
      const buffer = await file.arrayBuffer();
      const workbook = XLSX.read(buffer, { type: 'array' });
      const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
      if (!firstSheet) {
        toast({ title: 'خطأ', description: 'الملف لا يحتوي على أي ورقة', variant: 'destructive' });
        return;
      }

      const matrix = (XLSX.utils.sheet_to_json(firstSheet, { header: 1, defval: '' }) as Array<Array<unknown>>)
        .map((row) => row.map((cell) => String(cell ?? '').trim()));

      const nonEmptyRows = matrix.filter((row) => row.some((cell) => String(cell || '').trim().length > 0));
      if (nonEmptyRows.length < 2) {
        toast({ title: 'خطأ', description: 'الملف لا يحتوي على بيانات كافية', variant: 'destructive' });
        return;
      }

      // فك ترميز النصوص العربية المشوهة (Windows-1256 مقروءة كـ Latin-1)
      const decodeArabic = (text: string): string => {
        if (!text || /[\u0600-\u06FF]/.test(text)) return text;
        // إذا كل الأحرف في نطاق Latin-1 (< 256) جرب فك ترميز Windows-1256
        if ([...text].every((c) => c.charCodeAt(0) < 256)) {
          try {
            const bytes = new Uint8Array([...text].map((c) => c.charCodeAt(0)));
            const decoded = new TextDecoder('windows-1256').decode(bytes);
            if (/[\u0600-\u06FF]/.test(decoded)) return decoded;
          } catch {}
        }
        return text;
      };

      const headers = nonEmptyRows[0].map(decodeArabic);
      const dataRows = nonEmptyRows.slice(1).map((row) => row.map(decodeArabic));
      setPendingColumnMap({
        headers,
        previewRows: dataRows.slice(0, 3),
        dataRows,
        fileName: file.name,
      });
    } catch {
      toast({ title: 'خطأ', description: 'تعذر قراءة ملف Excel/CSV', variant: 'destructive' });
    } finally {
      event.target.value = '';
    }
  };

  const handleColumnMapConfirm = async (mapping: Record<string, string>) => {
    if (!pendingColumnMap) return;
    setIsImporting(true);
    try {
      // Build transactions array from mapping
      const txns = pendingColumnMap.dataRows.map((row) => {
        const obj: any = {};
        for (let i = 0; i < pendingColumnMap.headers.length; ++i) {
          const field = mapping[pendingColumnMap.headers[i]];
          if (!field) continue;
          obj[field] = row[i];
        }
        // Special: if both debit/credit present, compute amount/direction
        if (obj.debit && obj.credit) {
          const debit = Number(obj.debit) || 0;
          const credit = Number(obj.credit) || 0;
          if (debit > 0) {
            obj.amount = debit;
            obj.direction = 'outward';
          } else if (credit > 0) {
            obj.amount = credit;
            obj.direction = 'inward';
          }
        }
        // Fallback: if only amount, try direction
        if (obj.amount && !obj.direction) {
          obj.direction = 'inward';
        }
        return obj;
      }).filter((t: any) => t.amount && t.transactionDate);
      if (!txns.length) {
        toast({ title: 'خطأ', description: 'لم يتم العثور على حركات صالحة بعد الربط', variant: 'destructive' });
        return;
      }
      setStagedTransactions(txns);
      setImportFileName(pendingColumnMap.fileName);
      setPendingColumnMap(null);
      toast({ title: 'نجاح', description: `تم تجهيز ${txns.length} حركة للاستيراد` });
    } finally {
      setIsImporting(false);
    }
  };

  const [pendingColumnMap, setPendingColumnMap] = useState<null | {
    headers: string[];
    previewRows: string[][];
    dataRows: string[][];
    fileName: string;
  }>(null);
  const [isImporting, setIsImporting] = useState(false);

  const runPreview = async () => {
    if (!selectedPeriodId) {
      toast({ title: 'تنبيه', description: 'يرجى اختيار فترة أولاً', variant: 'destructive' });
      return;
    }

    const response = await fetch(
      `/api/admin/bank-reconciliation/periods/${encodeURIComponent(selectedPeriodId)}/auto-match/preview`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ threshold: Number(threshold || 80) }),
      }
    );

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      toast({ title: 'خطأ', description: String(err?.error || 'تعذر تشغيل المعاينة'), variant: 'destructive' });
      return;
    }

    const result = (await response.json()) as PreviewResponse;
    setPreviewResult(result);
    setApplyResult(null);
    toast({ title: 'نجاح', description: `تم توليد ${result.suggestions.length} اقتراح مطابقة` });
  };

  const applyFromPreview = async (dryRun: boolean) => {
    if (!selectedPeriodId) {
      toast({ title: 'تنبيه', description: 'يرجى اختيار فترة أولاً', variant: 'destructive' });
      return;
    }

    const response = await fetch(
      `/api/admin/bank-reconciliation/periods/${encodeURIComponent(selectedPeriodId)}/auto-match/apply`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          matchedBy: matchedBy || 'system',
          applyFromPreview: true,
          threshold: Number(threshold || 80),
          dryRun,
        }),
      }
    );

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      toast({ title: 'خطأ', description: String(err?.error || 'تعذر تطبيق التسوية'), variant: 'destructive' });
      return;
    }

    const result = (await response.json()) as ApplyResponse;
    setApplyResult(result);
    toast({
      title: dryRun ? 'تم تنفيذ Dry Run' : 'تم تطبيق التسوية',
      description: `Applied: ${result.appliedCount}, Skipped: ${result.skippedCount}`,
    });

    if (!dryRun) {
      void fetchPeriods(bankId);
    }
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>التسوية البنكية</CardTitle>
          <CardDescription>
            إنشاء فترة تسوية، استيراد كشف البنك، تشغيل المطابقة التلقائية، ثم التطبيق أو المعاينة Dry Run.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 gap-3 md:grid-cols-3">
            <div className="space-y-2">
              <Label>البنك</Label>
              <Select value={bankId} onValueChange={setBankId}>
                <SelectTrigger>
                  <SelectValue placeholder={loadingBanks ? 'جاري تحميل البنوك...' : 'اختر بنك'} />
                </SelectTrigger>
                <SelectContent>
                  {banks.map((bank) => (
                    <SelectItem key={bank.id} value={bank.id}>
                      {bank.fullName || bank.name || bank.code}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>المستخدم المنفذ</Label>
              <Input value={matchedBy} onChange={(e) => setMatchedBy(e.target.value)} placeholder="matchedBy" />
            </div>

            <div className="space-y-2">
              <Label>عتبة المطابقة (threshold)</Label>
              <Input type="number" min={0} max={100} value={threshold} onChange={(e) => setThreshold(e.target.value)} />
            </div>
          </div>

          <div className="grid grid-cols-1 gap-3 md:grid-cols-5">
            <div className="space-y-2">
              <Label>من تاريخ</Label>
              <Input type="date" value={periodStartDate} onChange={(e) => setPeriodStartDate(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>إلى تاريخ</Label>
              <Input type="date" value={periodEndDate} onChange={(e) => setPeriodEndDate(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>رصيد بداية كشف البنك</Label>
              <Input type="number" value={statementStartBalance} onChange={(e) => setStatementStartBalance(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>رصيد نهاية كشف البنك</Label>
              <Input type="number" value={statementEndBalance} onChange={(e) => setStatementEndBalance(e.target.value)} />
            </div>
            <div className="flex items-end">
              <Button onClick={createPeriod} className="w-full">إنشاء فترة</Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>الفترات</CardTitle>
          <CardDescription>اختر فترة تسوية للعمل عليها</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="mb-4">
            <Select value={selectedPeriodId} onValueChange={setSelectedPeriodId}>
              <SelectTrigger>
                <SelectValue placeholder={loadingPeriods ? 'جاري تحميل الفترات...' : 'اختر فترة'} />
              </SelectTrigger>
              <SelectContent>
                {periods.map((period) => (
                  <SelectItem key={period.id} value={period.id}>
                    {period.periodStartDate} → {period.periodEndDate} ({period.status})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="rounded-md border overflow-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>الفترة</TableHead>
                  <TableHead>الحالة</TableHead>
                  <TableHead>رصيد البداية</TableHead>
                  <TableHead>رصيد النهاية</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {periods.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center text-muted-foreground py-8">
                      لا توجد فترات بعد
                    </TableCell>
                  </TableRow>
                ) : (
                  periods.map((period) => (
                    <TableRow
                      key={period.id}
                      className={period.id === selectedPeriodId ? 'bg-primary/5 cursor-pointer' : 'cursor-pointer'}
                      onClick={() => setSelectedPeriodId(period.id)}
                    >
                      <TableCell>{period.periodStartDate} → {period.periodEndDate}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{period.status}</Badge>
                      </TableCell>
                      <TableCell>{period.statementStartBalance ?? 0}</TableCell>
                      <TableCell>{period.statementEndBalance}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>استيراد كشف البنك</CardTitle>
          <CardDescription>
            للمستخدم العادي: أدخل الحركات من النموذج المبسط ثم اضغط استيراد. JSON خيار متقدم فقط.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="rounded-lg border p-3 space-y-2">
            <p className="text-sm font-medium">استيراد من ملف Excel / CSV</p>
            <Input type="file" accept=".xlsx,.xls,.csv" onChange={handleImportFileChange} />
            <p className="text-xs text-muted-foreground">
              {importFileName ? `الملف الحالي: ${importFileName}` : 'ارفع ملفًا يحتوي أعمدة مثل: التاريخ، المبلغ، الاتجاه، الوصف.'}
            </p>
          </div>

          {/* Column mapping UI */}
          {pendingColumnMap && (
            <div className="rounded-lg border p-3 my-2 bg-muted/30">
              <p className="text-sm font-medium mb-2">تحديد نوع كل عمود</p>
              <BankStatementColumnMapper
                headers={pendingColumnMap.headers}
                previewRows={pendingColumnMap.previewRows}
                onConfirm={handleColumnMapConfirm}
                loading={isImporting}
              />
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-4 gap-2">
            <Input placeholder="المرجع البنكي" value={draftTxn.bankReference} onChange={(e) => setDraftTxn((p) => ({ ...p, bankReference: e.target.value }))} />
            <Select value={draftTxn.type} onValueChange={(v: DraftBankTransaction['type']) => setDraftTxn((p) => ({ ...p, type: v }))}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="transfer">حوالة</SelectItem>
                <SelectItem value="check">شيك</SelectItem>
                <SelectItem value="fee">رسوم</SelectItem>
                <SelectItem value="interest">فائدة</SelectItem>
                <SelectItem value="charge">تحميل</SelectItem>
                <SelectItem value="other">أخرى</SelectItem>
              </SelectContent>
            </Select>
            <Input placeholder="العملة (USD)" value={draftTxn.currencyCode} onChange={(e) => setDraftTxn((p) => ({ ...p, currencyCode: e.target.value }))} />
            <Button type="button" onClick={addStagedTransaction}>إضافة حركة</Button>
          </div>

          {stagedTransactions.length > 0 && (
            <div className="rounded border overflow-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>التاريخ</TableHead>
                    <TableHead>المبلغ</TableHead>
                    <TableHead>الاتجاه</TableHead>
                    <TableHead>الوصف</TableHead>
                    <TableHead>إجراء</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {stagedTransactions.map((txn, idx) => (
                    <TableRow key={`staged-${idx}`}>
                      <TableCell>{String(txn.transactionDate || '')}</TableCell>
                      <TableCell>{String(txn.amount || '')}</TableCell>
                      <TableCell>{String(txn.direction || '')}</TableCell>
                      <TableCell>{String(txn.description || '')}</TableCell>
                      <TableCell>
                        <Button type="button" size="sm" variant="destructive" onClick={() => removeStagedTransaction(idx)}>
                          حذف
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>المطابقة التلقائية</CardTitle>
          <CardDescription>
            تنفيذ معاينة أو تطبيق فعلي للفترة الحالية: {selectedPeriod ? `${selectedPeriod.periodStartDate} → ${selectedPeriod.periodEndDate}` : 'غير محددة'}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {!selectedPeriodId && (
            <p className="text-sm text-amber-600">الخطوة التالية: اختر فترة من جدول الفترات أولاً لتفعيل الأزرار.</p>
          )}
          <div className="flex flex-wrap gap-2">
            <Button onClick={runPreview} disabled={!selectedPeriodId}>معاينة المطابقة</Button>
            <Button onClick={() => applyFromPreview(true)} variant="outline" disabled={!selectedPeriodId}>تجربة بدون حفظ (Dry Run)</Button>
            <Button onClick={() => applyFromPreview(false)} disabled={!selectedPeriodId}>تطبيق التسوية من المعاينة</Button>
          </div>

          {previewResult && (
            <div className="rounded-lg border p-3 text-sm space-y-2">
              <div className="flex flex-wrap gap-3">
                <Badge variant="secondary">Suggestions: {previewResult.suggestions.length}</Badge>
                <Badge variant="secondary">Unmatched Bank: {previewResult.unmatchedBank.length}</Badge>
                <Badge variant="secondary">Unmatched Ledger: {previewResult.unmatchedLedger.length}</Badge>
              </div>
              <pre className="overflow-auto rounded bg-muted p-3 text-xs">{JSON.stringify(previewResult, null, 2)}</pre>
            </div>
          )}

          {applyResult && (
            <div className="rounded-lg border p-3 text-sm space-y-2">
              <div className="flex flex-wrap gap-3">
                <Badge>Applied: {applyResult.appliedCount}</Badge>
                <Badge variant="outline">Skipped: {applyResult.skippedCount}</Badge>
                <Badge variant="secondary">Matched: {applyResult.matchedCount}</Badge>
                {applyResult.dryRun ? <Badge variant="destructive">Dry Run</Badge> : null}
              </div>
              <pre className="overflow-auto rounded bg-muted p-3 text-xs">{JSON.stringify(applyResult, null, 2)}</pre>
            </div>
          )}
        </CardContent>
      </Card>

      {/* ── Professional Reconciliation Workspace ── */}
      {selectedPeriod && (
        <div className="space-y-2">
          <div className="flex items-center gap-2 px-1">
            <div className="h-px flex-1 bg-border" />
            <span className="text-xs text-muted-foreground font-medium uppercase tracking-wide">
              بيئة العمل الاحترافية
            </span>
            <div className="h-px flex-1 bg-border" />
          </div>
          <BankReconciliationWorkspace
            period={selectedPeriod}
            matchedBy={matchedBy}
            onPeriodUpdated={(updated) => {
              setPeriods((prev) => prev.map((p) => (p.id === updated.id ? updated : p)));
            }}
          />
        </div>
      )}
    </div>
  );
}
