'use client';

import { useMemo, useState } from 'react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { format } from 'date-fns';
import { CheckCircle2, XCircle, RotateCcw, Share2 } from 'lucide-react';
import { formatCurrency } from '@/lib/currency-formatter';
import { useToast } from '@/hooks/use-toast';
import { EndorseCheckDialog } from '@/components/admin/endorse-check-dialog';

type IncomingChecksClientProps = {
  checks: any[];
  customers: any[];
  suppliers: any[];
  collectionAccountsReady?: boolean;
  t: any;
  currencySymbol?: string;
};

export function IncomingChecksClient({
  checks,
  customers,
  suppliers,
  collectionAccountsReady = true,
  t,
  currencySymbol = '$'
}: IncomingChecksClientProps) {
  const { toast } = useToast();
  const [endorseDialogOpen, setEndorseDialogOpen] = useState(false);
  const [selectedCheckId, setSelectedCheckId] = useState<string>('');
  const [selectedCheckNumber, setSelectedCheckNumber] = useState<string>('');
  const [selectedCheckAmount, setSelectedCheckAmount] = useState<number>(0);
  const [returnDialogOpen, setReturnDialogOpen] = useState(false);
  const [selectedReturnCheck, setSelectedReturnCheck] = useState<any | null>(null);
  const [returnReason, setReturnReason] = useState('');
  const [returnBankFee, setReturnBankFee] = useState('0');
  const [chargeFeeToCustomer, setChargeFeeToCustomer] = useState(false);
  const [returnNotes, setReturnNotes] = useState('');
  const [returnDate, setReturnDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [isSubmittingReturn, setIsSubmittingReturn] = useState(false);
  const [clearDialogOpen, setClearDialogOpen] = useState(false);
  const [rejectDialogOpen, setRejectDialogOpen] = useState(false);
  const [selectedActionCheck, setSelectedActionCheck] = useState<any | null>(null);
  const [actionDate, setActionDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [actionNotes, setActionNotes] = useState('');
  const [rejectReason, setRejectReason] = useState('');
  const [isSubmittingAction, setIsSubmittingAction] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [endorsementFilter, setEndorsementFilter] = useState('all');
  const [bankFilter, setBankFilter] = useState('all');
  const [customerFilter, setCustomerFilter] = useState('all');
  const [fromDate, setFromDate] = useState('');
  const [toDate, setToDate] = useState('');
  const [minAmount, setMinAmount] = useState('');
  const [maxAmount, setMaxAmount] = useState('');
  const [smartPreset, setSmartPreset] = useState('all');

  const today = useMemo(() => format(new Date(), 'yyyy-MM-dd'), []);
  const sevenDaysAhead = useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() + 7);
    return format(d, 'yyyy-MM-dd');
  }, []);

  const bankOptions = useMemo(() => {
    return Array.from(new Set((checks || []).map((c) => String(c.bankName || '').trim()).filter(Boolean))).sort((a, b) => a.localeCompare(b, 'ar'));
  }, [checks]);

  const customerOptions = useMemo(() => {
    return Array.from(new Set((checks || []).map((c) => String(c.customerName || '').trim()).filter(Boolean))).sort((a, b) => a.localeCompare(b, 'ar'));
  }, [checks]);

  const filteredChecks = useMemo(() => {
    const min = minAmount.trim() === '' ? null : Number(minAmount);
    const max = maxAmount.trim() === '' ? null : Number(maxAmount);
    const q = searchQuery.trim().toLowerCase();

    return (checks || []).filter((check) => {
      const checkDate = format(new Date(check.checkDate), 'yyyy-MM-dd');
      const amount = Number(check.amount || 0);
      const endorsementStatus = String(check.endorsementStatus || 'none').trim();
      const isEndorsed = endorsementStatus !== '' && endorsementStatus !== 'none';
      const text = [
        String(check.checkNumber || ''),
        String(check.bankName || ''),
        String(check.customerName || ''),
        String(check.currency || ''),
        String(check.status || ''),
      ].join(' ').toLowerCase();

      if (q && !text.includes(q)) return false;
      if (statusFilter !== 'all' && String(check.status || '').trim() !== statusFilter) return false;
      if (endorsementFilter !== 'all') {
        if (endorsementFilter === 'not-endorsed' && isEndorsed) return false;
        if (endorsementFilter === 'endorsed' && !isEndorsed) return false;
      }
      if (bankFilter !== 'all' && String(check.bankName || '').trim() !== bankFilter) return false;
      if (customerFilter !== 'all' && String(check.customerName || '').trim() !== customerFilter) return false;
      if (fromDate && checkDate < fromDate) return false;
      if (toDate && checkDate > toDate) return false;
      if (min !== null && Number.isFinite(min) && amount < min) return false;
      if (max !== null && Number.isFinite(max) && amount > max) return false;

      if (smartPreset === 'overdue-pending' && !(String(check.status || '').trim() === 'pending' && checkDate < today)) return false;
      if (smartPreset === 'due-this-week' && !(String(check.status || '').trim() === 'pending' && checkDate >= today && checkDate <= sevenDaysAhead)) return false;
      if (smartPreset === 'high-value' && !(amount >= 10000)) return false;
      if (smartPreset === 'return-risk' && !['rejected', 'returned'].includes(String(check.status || '').trim())) return false;
      if (smartPreset === 'supplier-endorsed' && !(endorsementStatus === 'endorsed-to-party' && String(check.endorsedToType || '').trim() === 'supplier')) return false;

      return true;
    });
  }, [checks, minAmount, maxAmount, searchQuery, statusFilter, endorsementFilter, bankFilter, customerFilter, fromDate, toDate, smartPreset, today, sevenDaysAhead]);

  const smartSummary = useMemo(() => {
    const rows = filteredChecks;
    const totalAmount = rows.reduce((sum, row) => sum + Number(row.amount || 0), 0);
    const pending = rows.filter((row) => String(row.status || '').trim() === 'pending');
    const cleared = rows.filter((row) => String(row.status || '').trim() === 'cleared');
    const returnedOrRejected = rows.filter((row) => ['rejected', 'returned'].includes(String(row.status || '').trim()));

    const pendingAmount = pending.reduce((sum, row) => sum + Number(row.amount || 0), 0);
    const clearedAmount = cleared.reduce((sum, row) => sum + Number(row.amount || 0), 0);

    const overduePendingCount = pending.filter((row) => format(new Date(row.checkDate), 'yyyy-MM-dd') < today).length;
    const dueSoonCount = pending.filter((row) => {
      const d = format(new Date(row.checkDate), 'yyyy-MM-dd');
      return d >= today && d <= sevenDaysAhead;
    }).length;

    const collectionRate = totalAmount > 0 ? (clearedAmount / totalAmount) * 100 : 0;

    const bankMap = new Map<string, { count: number; amount: number }>();
    rows.forEach((row) => {
      const bank = String(row.bankName || '-').trim() || '-';
      const current = bankMap.get(bank) || { count: 0, amount: 0 };
      current.count += 1;
      current.amount += Number(row.amount || 0);
      bankMap.set(bank, current);
    });

    const topBanks = Array.from(bankMap.entries())
      .map(([bank, stats]) => ({ bank, ...stats }))
      .sort((a, b) => b.amount - a.amount)
      .slice(0, 5);

    return {
      totalCount: rows.length,
      totalAmount,
      pendingCount: pending.length,
      pendingAmount,
      returnedCount: returnedOrRejected.length,
      overduePendingCount,
      dueSoonCount,
      collectionRate,
      topBanks,
    };
  }, [filteredChecks, today, sevenDaysAhead]);

  const clearFilters = () => {
    setSearchQuery('');
    setStatusFilter('all');
    setEndorsementFilter('all');
    setBankFilter('all');
    setCustomerFilter('all');
    setFromDate('');
    setToDate('');
    setMinAmount('');
    setMaxAmount('');
    setSmartPreset('all');
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'pending':
        return <Badge variant="outline">{t.statusPending ?? 'قيد الانتظار'}</Badge>;
      case 'cleared':
        return <Badge variant="default" className="bg-green-600">{t.statusCleared ?? 'مقبول'}</Badge>;
      case 'rejected':
        return <Badge variant="destructive">{t.statusRejected ?? 'مرفوض'}</Badge>;
      case 'returned':
        return <Badge variant="secondary">{t.statusReturned ?? 'مرجع'}</Badge>;
      default:
        return <Badge>{status}</Badge>;
    }
  };

  const getEndorsementBadge = (check: any) => {
    const endorsementStatus = String(check.endorsementStatus || 'none').trim();
    if (endorsementStatus === 'endorsed-to-party') {
      return <Badge className="bg-blue-600 text-white">{t.endorsed ?? 'مجيّر'}</Badge>;
    }
    if (endorsementStatus === 'transferred-to-collection') {
      return <Badge variant="secondary">{t.transferredToCollection ?? 'برسم التحصيل'}</Badge>;
    }
    return <Badge variant="outline">{t.notEndorsed ?? 'غير مظهّر'}</Badge>;
  };

  const getEndorsementDetails = (check: any) => {
    const endorsementStatus = String(check.endorsementStatus || 'none').trim();
    if (endorsementStatus === 'none' || endorsementStatus === '') {
      return (t.noEndorsementDetails ?? 'لا يوجد تجيير مسجل');
    }

    const partyType = String(check.endorsedToType || '').trim() === 'supplier' ? (t.supplier ?? 'مورد') : (t.customer ?? 'عميل');
    const party = String(check.endorsedToName || '').trim();
    const ref = String(check.endorsementReference || check.reservedByPurchaseOrderId || '').trim();
    const endorsedAt = String(check.endorsedAt || '').trim();
    const dateText = endorsedAt ? format(new Date(endorsedAt), 'yyyy-MM-dd') : '-';

    if (endorsementStatus === 'transferred-to-collection') {
      return `${t.transferredToCollection ?? 'تم تحويل الشيك للتحصيل'} | ${t.date ?? 'التاريخ'}: ${dateText}`;
    }

    const lines = [
      `${partyType}: ${party || '-'}`,
      `${t.endorsementDate ?? 'تاريخ التجيير'}: ${dateText}`,
      `${t.endorsementReference ?? 'مرجع السند/الفاتورة'}: ${ref || '-'}`,
    ];

    return lines.join(' | ');
  };

  const openClearDialog = (check: any) => {
    setSelectedActionCheck(check);
    setActionDate(format(new Date(), 'yyyy-MM-dd'));
    setActionNotes('');
    setClearDialogOpen(true);
  };

  const openRejectDialog = (check: any) => {
    setSelectedActionCheck(check);
    setActionDate(format(new Date(), 'yyyy-MM-dd'));
    setActionNotes('');
    setRejectReason('');
    setRejectDialogOpen(true);
  };

  const submitMarkStatus = async (action: 'cleared' | 'rejected') => {
    if (!selectedActionCheck) return;
    if (action === 'rejected' && !rejectReason.trim()) {
      toast({ title: t.error ?? 'خطأ', description: t.rejectReasonRequired ?? 'سبب رفض الشيك مطلوب', variant: 'destructive' });
      return;
    }
    try {
      setIsSubmittingAction(true);
      const response = await fetch('/api/admin/checks/mark-status', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          checkId: selectedActionCheck.id,
          action,
          date: actionDate,
          notes: actionNotes.trim() || undefined,
          rejectedReason: action === 'rejected' ? rejectReason.trim() : undefined,
        }),
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        toast({ title: t.error ?? 'خطأ', description: payload?.error || t.operationFailed || 'فشلت العملية', variant: 'destructive' });
        return;
      }
      toast({
        title: t.success ?? 'نجاح',
        description: action === 'cleared'
          ? (t.checkClearedSuccess ?? 'تم تأكيد صرف الشيك بنجاح وتسجيل القيد المحاسبي')
          : (t.checkRejectedSuccess ?? 'تم تسجيل رفض الشيك وإعادة إثبات الذمة'),
      });
      setClearDialogOpen(false);
      setRejectDialogOpen(false);
      window.location.reload();
    } catch {
      toast({ title: t.error ?? 'خطأ', description: t.operationFailed ?? 'فشلت العملية', variant: 'destructive' });
    } finally {
      setIsSubmittingAction(false);
    }
  };

  const handleEndorseClick = (checkId: string, checkNumber: string, amount: number) => {
    setSelectedCheckId(checkId);
    setSelectedCheckNumber(checkNumber);
    setSelectedCheckAmount(amount);
    setEndorseDialogOpen(true);
  };

  const openReturnDialog = (check: any) => {
    setSelectedReturnCheck(check);
    setReturnReason('');
    setReturnBankFee('0');
    setChargeFeeToCustomer(false);
    setReturnNotes('');
    setReturnDate(format(new Date(), 'yyyy-MM-dd'));
    setReturnDialogOpen(true);
  };

  const submitReturnCheck = async () => {
    if (!selectedReturnCheck) return;

    const reason = returnReason.trim();
    if (!reason) {
      toast({
        title: t.error ?? 'خطأ',
        description: t.returnReasonRequired ?? 'سبب ارتجاع الشيك مطلوب',
        variant: 'destructive',
      });
      return;
    }

    const bankFeeAmount = Number(returnBankFee || 0);
    if (!Number.isFinite(bankFeeAmount) || bankFeeAmount < 0) {
      toast({
        title: t.error ?? 'خطأ',
        description: t.invalidAmount ?? 'قيمة غير صالحة',
        variant: 'destructive',
      });
      return;
    }

    try {
      setIsSubmittingReturn(true);
      const response = await fetch('/api/admin/checks/return', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          checkId: selectedReturnCheck.id,
          reason,
          bankFeeAmount,
          chargeFeeToCustomer,
          returnedDate: returnDate,
          notes: returnNotes.trim() || undefined,
        }),
      });

      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        toast({
          title: t.error ?? 'خطأ',
          description: payload?.error || t.operationFailed || 'فشلت العملية',
          variant: 'destructive',
        });
        return;
      }

      toast({
        title: t.success ?? 'نجاح',
        description: t.returnProcessedSuccess ?? 'تم تسجيل ارتجاع الشيك بنجاح',
      });
      setReturnDialogOpen(false);
      window.location.reload();
    } catch {
      toast({
        title: t.error ?? 'خطأ',
        description: t.operationFailed ?? 'فشلت العملية',
        variant: 'destructive',
      });
    } finally {
      setIsSubmittingReturn(false);
    }
  };

  return (
    <>
      <Card className="bg-white shadow-sm border-0">
        <CardHeader>
          <CardTitle className="text-lg">{t.filtersTitle ?? 'الفلاتر والبحث'}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-wrap items-center gap-2">
            <Input
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder={t.searchPlaceholder ?? 'بحث ذكي: رقم الشيك / البنك / العميل / العملة / الحالة'}
              className="w-full md:w-[360px] bg-white"
            />

            <select value={smartPreset} onChange={(e) => setSmartPreset(e.target.value)} className="h-10 rounded-md border bg-white px-3 py-2 text-sm">
              <option value="all">{t.smartPresetAll ?? 'كل السجلات'}</option>
            <option value="overdue-pending">{t.smartPresetOverdue ?? 'شيكات متأخرة (Pending)'}</option>
            <option value="due-this-week">{t.smartPresetDueSoon ?? 'مستحق هذا الأسبوع'}</option>
            <option value="high-value">{t.smartPresetHighValue ?? 'قيمة عالية (>= 10,000)'}</option>
            <option value="return-risk">{t.smartPresetReturnRisk ?? 'مخاطر ارتجاع (مرفوض/مرتجع)'}</option>
            <option value="supplier-endorsed">{t.smartPresetEndorsedSupplier ?? 'مظهّر لمورد'}</option>
          </select>

          <Button variant="outline" onClick={clearFilters}>{t.clearFilters ?? 'إعادة ضبط الفلاتر'}</Button>
        </div>

        <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6">
          <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} className="h-10 rounded-md border bg-background px-3 text-sm">
            <option value="all">{t.allStatuses ?? 'كل الحالات'}</option>
            <option value="pending">{t.statusPending ?? 'قيد الانتظار'}</option>
            <option value="cleared">{t.statusCleared ?? 'مقبول'}</option>
            <option value="rejected">{t.statusRejected ?? 'مرفوض'}</option>
            <option value="returned">{t.statusReturned ?? 'مرجع'}</option>
          </select>

          <select value={endorsementFilter} onChange={(e) => setEndorsementFilter(e.target.value)} className="h-10 rounded-md border bg-white px-3 py-2 text-sm">
            <option value="all">{t.allEndorsements ?? 'كل حالات التجيير'}</option>
            <option value="not-endorsed">{t.notEndorsed ?? 'غير مظهّر'}</option>
            <option value="endorsed">{t.endorsed ?? 'مظهّر'}</option>
          </select>

          <select value={bankFilter} onChange={(e) => setBankFilter(e.target.value)} className="h-10 rounded-md border bg-white px-3 py-2 text-sm">
            <option value="all">{t.allBanks ?? 'كل البنوك'}</option>
            {bankOptions.map((bank) => (
              <option key={bank} value={bank}>{bank}</option>
            ))}
          </select>

          <select value={customerFilter} onChange={(e) => setCustomerFilter(e.target.value)} className="h-10 rounded-md border bg-white px-3 py-2 text-sm">
            <option value="all">{t.allCustomers ?? 'كل العملاء'}</option>
            {customerOptions.map((customer) => (
              <option key={customer} value={customer}>{customer}</option>
            ))}
          </select>

          <Input type="date" value={fromDate} onChange={(e) => setFromDate(e.target.value)} className="bg-white" />
          <Input type="date" value={toDate} onChange={(e) => setToDate(e.target.value)} className="bg-white" />
          <Input type="number" min="0" step="0.01" placeholder={t.minAmount ?? 'أقل مبلغ'} value={minAmount} onChange={(e) => setMinAmount(e.target.value)} className="bg-white" />
          <Input type="number" min="0" step="0.01" placeholder={t.maxAmount ?? 'أعلى مبلغ'} value={maxAmount} onChange={(e) => setMaxAmount(e.target.value)} className="bg-white" />
        </div>
        </CardContent>
      </Card>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Card className="bg-white">
          <CardContent className="pt-6">
            <div className="text-xs text-muted-foreground">{t.totalChecks ?? 'إجمالي الشيكات (بعد الفلترة)'}</div>
            <div className="text-2xl font-bold mt-2">{smartSummary.totalCount}</div>
            <div className="text-sm text-muted-foreground mt-1">{formatCurrency(smartSummary.totalAmount, currencySymbol)}</div>
          </CardContent>
        </Card>
        <Card className="bg-white">
          <CardContent className="pt-6">
            <div className="text-xs text-muted-foreground">{t.pendingChecks ?? 'الشيكات قيد الانتظار'}</div>
            <div className="text-2xl font-bold mt-2">{smartSummary.pendingCount}</div>
            <div className="text-sm text-muted-foreground mt-1">{formatCurrency(smartSummary.pendingAmount, currencySymbol)}</div>
          </CardContent>
        </Card>
        <Card className="bg-white">
          <CardContent className="pt-6">
            <div className="text-xs text-muted-foreground">{t.riskIndicators ?? 'مؤشرات المخاطر'}</div>
            <div className="space-y-2 mt-3">
              <div className="text-sm">{t.overdue ?? 'متأخر'}: <span className="font-semibold text-red-600">{smartSummary.overduePendingCount}</span></div>
              <div className="text-sm">{t.dueSoon ?? 'مستحق قريبًا'}: <span className="font-semibold text-amber-600">{smartSummary.dueSoonCount}</span></div>
              <div className="text-sm">{t.returnedOrRejected ?? 'مرتجع/مرفوض'}: <span className="font-semibold text-orange-600">{smartSummary.returnedCount}</span></div>
            </div>
          </CardContent>
        </Card>
        <Card className="bg-white">
          <CardContent className="pt-6">
            <div className="text-xs text-muted-foreground">{t.collectionEfficiency ?? 'كفاءة التحصيل'}</div>
            <div className="text-2xl font-bold mt-2 text-green-600">{smartSummary.collectionRate.toFixed(1)}%</div>
            <div className="text-sm text-muted-foreground mt-1">{t.basedOnVisibleData ?? 'محسوبة من البيانات الظاهرة'}</div>
          </CardContent>
        </Card>
      </div>

      <Card className="bg-white shadow-sm border-0">
        <CardHeader>
          <CardTitle className="text-base">{t.topBanksByAmount ?? 'أعلى البنوك حسب قيمة الشيكات (بعد الفلترة)'}</CardTitle>
        </CardHeader>
        <CardContent>
          {smartSummary.topBanks.length === 0 ? (
            <div className="text-sm text-muted-foreground py-4">{t.noData ?? 'لا توجد بيانات'}</div>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
              {smartSummary.topBanks.map((row) => (
                <div key={row.bank} className="rounded-lg border border-slate-200 bg-gradient-to-br from-blue-50 to-indigo-50 p-3 hover:shadow-md transition-shadow">
                  <div className="text-sm font-semibold text-slate-800 truncate" title={row.bank}>{row.bank}</div>
                  <div className="text-xs text-slate-500 mt-1">{row.count} {t.checksCount ?? 'شيك'}</div>
                  <div className="text-base font-bold text-blue-600 mt-2">{formatCurrency(row.amount, currencySymbol)}</div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Card className="bg-white">
        <CardHeader>
          <CardTitle className="text-base">{t.checksTableTitle ?? 'سجل الشيكات'}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="relative w-full overflow-auto">
            <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t.checkNumber ?? 'رقم الشيك'}</TableHead>
                <TableHead>{t.bankName ?? 'اسم البنك'}</TableHead>
                <TableHead>{t.customerName ?? 'اسم العميل'}</TableHead>
                <TableHead>{t.checkDate ?? 'تاريخ الشيك'}</TableHead>
                <TableHead className="text-right">{t.amount ?? 'المبلغ'}</TableHead>
                <TableHead>{t.currency ?? 'العملة'}</TableHead>
                <TableHead>{t.status ?? 'الحالة'}</TableHead>
                <TableHead>{t.endorsementStatus ?? 'حالة التجيير'}</TableHead>
                <TableHead>{t.endorsementDetails ?? 'تفاصيل التجيير'}</TableHead>
                <TableHead>{t.actions ?? 'الإجراءات'}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredChecks.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={10} className="text-center text-muted-foreground py-8">
                    {t.noChecksAfterFilter ?? 'لا توجد شيكات مطابقة للفلاتر الحالية'}
                  </TableCell>
                </TableRow>
              ) : (
                filteredChecks.map((check) => (
                  <TableRow key={check.id}>
                    <TableCell className="font-medium">{check.checkNumber}</TableCell>
                    <TableCell>{check.bankName}</TableCell>
                    <TableCell>{check.customerName || 'N/A'}</TableCell>
                    <TableCell>{format(new Date(check.checkDate), 'yyyy-MM-dd')}</TableCell>
                    <TableCell className="text-right">{formatCurrency(check.amount, currencySymbol)}</TableCell>
                    <TableCell>{check.currency}</TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-1">
                        {getStatusBadge(check.status)}
                        {String(check.endorsementStatus || 'none').trim() === 'endorsed-to-party' ? (
                          <Badge className="bg-blue-100 text-blue-800">{t.endorsedMarker ?? 'هذا الشيك مجيّر'}</Badge>
                        ) : null}
                      </div>
                    </TableCell>
                    <TableCell>{getEndorsementBadge(check)}</TableCell>
                    <TableCell className="max-w-[340px] text-xs leading-5 text-muted-foreground">{getEndorsementDetails(check)}</TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        {check.status === 'pending' && ['none', ''].includes(String(check.endorsementStatus || 'none').trim()) && (
                          <>
                            <Button
                              size="sm"
                              variant="outline"
                              title={t.endorseCheck ?? 'تجير الشيك'}
                              onClick={() =>
                                handleEndorseClick(check.id, check.checkNumber, check.amount)
                              }
                            >
                              <Share2 className="h-4 w-4" />
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              title={t.markCleared ?? 'تأكيد الصرف'}
                              onClick={() => openClearDialog(check)}
                            >
                              <CheckCircle2 className="h-4 w-4" />
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              title={t.markRejected ?? 'رفض الشيك'}
                              onClick={() => openRejectDialog(check)}
                            >
                              <XCircle className="h-4 w-4" />
                            </Button>
                          </>
                        )}
                        {check.endorsementStatus === 'endorsed-to-party' && check.endorsedToType === 'supplier' && check.status !== 'returned' && (
                          <Button
                            size="sm"
                            variant="outline"
                            title={t.returnEndorsedCheck ?? 'تسجيل شيك مرتجع'}
                            onClick={() => openReturnDialog(check)}
                          >
                            <RotateCcw className="h-4 w-4" />
                          </Button>
                        )}
                        {(check.status === 'rejected' || check.status === 'returned') && (
                          <Button
                            size="sm"
                            variant="outline"
                            title={t.returnToCustomer ?? 'إرجاع للعميل'}
                          >
                            <RotateCcw className="h-4 w-4" />
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
          </div>
        </CardContent>
      </Card>
      {/* ===== تأكيد الصرف Dialog ===== */}
      <Dialog open={clearDialogOpen} onOpenChange={setClearDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t.markCleared ?? 'تأكيد الصرف'}</DialogTitle>
            <DialogDescription>
              {selectedActionCheck
                ? `${t.checkNumber ?? 'رقم الشيك'}: ${selectedActionCheck.checkNumber} - ${t.amount ?? 'المبلغ'}: ${formatCurrency(selectedActionCheck.amount, currencySymbol)}`
                : ''}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="clear-date">{t.clearDate ?? 'تاريخ الصرف'}</Label>
              <Input
                id="clear-date"
                type="date"
                value={actionDate}
                onChange={(e) => setActionDate(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="clear-notes">{t.notes ?? 'ملاحظات'}</Label>
              <Textarea
                id="clear-notes"
                value={actionNotes}
                onChange={(e) => setActionNotes(e.target.value)}
                placeholder={t.optionalNotes ?? 'ملاحظات اختيارية...'}
                rows={2}
              />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setClearDialogOpen(false)} disabled={isSubmittingAction}>
              {t.cancel ?? 'إلغاء'}
            </Button>
            <Button type="button" onClick={() => submitMarkStatus('cleared')} disabled={isSubmittingAction}>
              {isSubmittingAction ? (t.processing ?? 'جاري المعالجة...') : (t.confirmClear ?? 'تأكيد الصرف')}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ===== رفض الشيك Dialog ===== */}
      <Dialog open={rejectDialogOpen} onOpenChange={setRejectDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t.markRejected ?? 'رفض الشيك'}</DialogTitle>
            <DialogDescription>
              {selectedActionCheck
                ? `${t.checkNumber ?? 'رقم الشيك'}: ${selectedActionCheck.checkNumber} - ${t.amount ?? 'المبلغ'}: ${formatCurrency(selectedActionCheck.amount, currencySymbol)}`
                : ''}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="reject-date">{t.rejectedDate ?? 'تاريخ الرفض'}</Label>
              <Input
                id="reject-date"
                type="date"
                value={actionDate}
                onChange={(e) => setActionDate(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="reject-reason">{t.rejectReason ?? 'سبب الرفض'} *</Label>
              <Textarea
                id="reject-reason"
                value={rejectReason}
                onChange={(e) => setRejectReason(e.target.value)}
                placeholder={t.rejectReasonPlaceholder ?? 'مثال: رصيد غير كافٍ، توقيع غير مطابق، حساب مغلق...'}
                rows={3}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="reject-notes">{t.notes ?? 'ملاحظات إضافية'}</Label>
              <Textarea
                id="reject-notes"
                value={actionNotes}
                onChange={(e) => setActionNotes(e.target.value)}
                placeholder={t.optionalNotes ?? 'ملاحظات اختيارية...'}
                rows={2}
              />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setRejectDialogOpen(false)} disabled={isSubmittingAction}>
              {t.cancel ?? 'إلغاء'}
            </Button>
            <Button type="button" variant="destructive" onClick={() => submitMarkStatus('rejected')} disabled={isSubmittingAction}>
              {isSubmittingAction ? (t.processing ?? 'جاري المعالجة...') : (t.confirmReject ?? 'تأكيد الرفض')}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={returnDialogOpen} onOpenChange={setReturnDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>{t.returnEndorsedCheck ?? 'تسجيل شيك مرتجع'}</DialogTitle>
            <DialogDescription>
              {selectedReturnCheck
                ? `${t.checkNumber ?? 'رقم الشيك'}: ${selectedReturnCheck.checkNumber} - ${t.amount ?? 'المبلغ'}: ${formatCurrency(selectedReturnCheck.amount, currencySymbol)}`
                : (t.returnCheckDescription ?? 'تسجيل حدث ارتجاع شيك مظهّر لمورد')}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="return-date">{t.returnDate ?? 'تاريخ الارتجاع'}</Label>
              <Input
                id="return-date"
                type="date"
                value={returnDate}
                onChange={(e) => setReturnDate(e.target.value)}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="return-reason">{t.returnReason ?? 'سبب الارتجاع'}</Label>
              <Textarea
                id="return-reason"
                value={returnReason}
                onChange={(e) => setReturnReason(e.target.value)}
                placeholder={t.returnReasonPlaceholder ?? 'مثال: عدم توفر أموال، حساب مغلق، توقيع غير صحيح...'}
                rows={3}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="return-bank-fee">{t.returnBankFee ?? 'رسوم البنك'}</Label>
              <Input
                id="return-bank-fee"
                type="number"
                min="0"
                step="0.01"
                placeholder={t.returnBankFeePlaceholder ?? '0.00'}
                value={returnBankFee}
                onChange={(e) => setReturnBankFee(e.target.value)}
              />
            </div>

            <div className="flex items-center justify-between rounded-md border px-3 py-2">
              <Label htmlFor="charge-fee-switch" className="text-sm">{t.chargeFeeToCustomer ?? 'فرض رسوم الارتجاع على العميل'}</Label>
              <Switch
                id="charge-fee-switch"
                checked={chargeFeeToCustomer}
                onCheckedChange={setChargeFeeToCustomer}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="return-notes">{t.returnNotes ?? 'ملاحظات إضافية'}</Label>
              <Textarea
                id="return-notes"
                value={returnNotes}
                onChange={(e) => setReturnNotes(e.target.value)}
                placeholder={t.returnNotesPlaceholder ?? 'أدخل أي ملاحظات إضافية...'}
                rows={2}
              />
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setReturnDialogOpen(false)} disabled={isSubmittingReturn}>
              {t.cancel ?? 'إلغاء'}
            </Button>
            <Button type="button" onClick={submitReturnCheck} disabled={isSubmittingReturn}>
              {isSubmittingReturn ? (t.processing ?? 'جاري المعالجة...') : (t.confirmReturn ?? 'تأكيد الارتجاع')}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <EndorseCheckDialog
        open={endorseDialogOpen}
        onOpenChange={setEndorseDialogOpen}
        checkId={selectedCheckId}
        checkNumber={selectedCheckNumber}
        amount={selectedCheckAmount}
        customers={customers}
        suppliers={suppliers}
        collectionAccountsReady={collectionAccountsReady}
        t={t}
      />

    </>
  );
}
