'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import type { SalesInvoice, SalesInvoicePaymentMethod } from '@/lib/modules/sales';
import { formatDateStable } from '@/lib/formatters';
import {
  handleCreateSalesPaymentReceipt,
  handleCancelSalesPaymentReceipt,
  handleUpdateSalesPaymentReceipt,
} from '@/lib/actions/sales-invoice.actions';
import type { Bank, Currency, CustomerPayment, GeneralBank } from '@/lib/types';
import { useToast } from '@/hooks/use-toast';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Trash2, ChevronDown } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogDescription,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';

const PAYMENT_METHODS: SalesInvoicePaymentMethod['method'][] = [
  'cash',
  'check',
  'bank_transfer',
  'credit',
];

const PAYMENT_METHOD_LABELS: Record<SalesInvoicePaymentMethod['method'], string> = {
  cash: 'نقدًا',
  check: 'شيك',
  bank_transfer: 'تحويل بنكي',
  credit: 'ذمم',
};

function buildShortReceiptReference(paymentId?: string): string {
  const normalized = String(paymentId || '').trim();
  if (!normalized) return 'يولد تلقائيًا عند الحفظ';
  const raw = normalized.replace(/^pay-/i, '');
  const token = String(raw.split('-')[0] || raw).slice(0, 8).toUpperCase();
  return `RCP-${token || 'AUTO'}`;
}

function resolveReceiptReference(payment: Partial<CustomerPayment>): string {
  const savedReference = String(payment.reference || '').trim();
  if (savedReference) return savedReference;
  return buildShortReceiptReference(String(payment.id || ''));
}

type ReceiptCheckRow = {
  checkNumber: string;
  bankId?: string;
  bankName: string;
  checkDate: string;
  amount: string;
  currency: string;
  reference: string;
  status: 'pending' | 'cleared' | 'rejected' | 'returned';
};

type AddGeneralBankDraft = {
  code: string;
  name: string;
  nameEn: string;
  branch: string;
};

function createEmptyCheckRow(defaultCurrencyCode: string): ReceiptCheckRow {
  return {
    checkNumber: '',
    bankId: '',
    bankName: '',
    checkDate: new Date().toISOString().slice(0, 10),
    amount: '',
    currency: defaultCurrencyCode,
    reference: '',
    status: 'pending',
  };
}

type SalesPaymentReceivedClientProps = {
  invoices: SalesInvoice[];
  payments: CustomerPayment[];
  currencies: Currency[];
  banks: (Bank | GeneralBank)[];
  defaultCurrencyCode: string;
  editPaymentId?: string;
  userId: string;
  userName: string;
};

export default function SalesPaymentReceivedClient({
  invoices,
  payments,
  currencies,
  banks,
  defaultCurrencyCode,
  editPaymentId,
  userId,
  userName,
}: SalesPaymentReceivedClientProps) {
  const router = useRouter();
  const { toast } = useToast();
  const formNavRef = useRef<HTMLDivElement | null>(null);
  const [bankOptions, setBankOptions] = useState<(Bank | GeneralBank)[]>(banks || []);
  const [selectedCustomerId, setSelectedCustomerId] = useState('');
  const [amount, setAmount] = useState('');
  const [method, setMethod] = useState<SalesInvoicePaymentMethod['method']>('cash');
  const postingStatus: 'posted' = 'posted';
  const [currencyCode, setCurrencyCode] = useState(defaultCurrencyCode);
  const [exchangeRate, setExchangeRate] = useState('1');
  const [rateDate, setRateDate] = useState(() => new Date().toISOString().slice(0, 10));
  const [voucherDate, setVoucherDate] = useState(() => new Date().toISOString().slice(0, 10));
  const [isAdvance, setIsAdvance] = useState(false);
  const [reference, setReference] = useState('');
  const [notes, setNotes] = useState('');
  const [checkRows, setCheckRows] = useState<ReceiptCheckRow[]>([createEmptyCheckRow(defaultCurrencyCode)]);
  const [allocationDrafts, setAllocationDrafts] = useState<Record<string, string>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isCancellingId, setIsCancellingId] = useState('');
  const [editingPaymentId, setEditingPaymentId] = useState('');
  const [recentPaymentsSearch, setRecentPaymentsSearch] = useState('');
  const [isAddBankDialogOpen, setIsAddBankDialogOpen] = useState(false);
  const [pendingBankRowIndex, setPendingBankRowIndex] = useState<number | null>(null);
  const [isCreatingBank, setIsCreatingBank] = useState(false);
  const [newBankDraft, setNewBankDraft] = useState<AddGeneralBankDraft>({
    code: '',
    name: '',
    nameEn: '',
    branch: '',
  });
  const editingPaymentReference = useMemo(() => {
    if (!editingPaymentId) return '';
    const target = (payments || []).find((entry) => String(entry.id || '') === editingPaymentId);
    return String(target?.reference || '').trim();
  }, [editingPaymentId, payments]);
  const shortReceiptReference = useMemo(() => {
    return editingPaymentReference || buildShortReceiptReference(editingPaymentId);
  }, [editingPaymentReference, editingPaymentId]);
  const { lockStatus } = useDocumentLock('customer-payment', editingPaymentId || '', { enabled: !!editingPaymentId });
  const isEditLocked = !!editingPaymentId && lockStatus.isLocked;

  const dueInvoices = useMemo(
    () => invoices.filter((invoice) => {
      const status = String(invoice.status || '').toLowerCase();
      return status !== 'cancelled' && status !== 'draft' && Number(invoice.amountDue || 0) > 0;
    }),
    [invoices]
  );

  const customerNamesById = useMemo(() => {
    const map = new Map<string, string>();
    for (const invoice of invoices) {
      const customerId = String(invoice.customerId || '').trim();
      const customerName = String(invoice.customerName || '').trim();
      if (!customerId || !customerName || map.has(customerId)) continue;
      map.set(customerId, customerName);
    }
    return map;
  }, [invoices]);

  const customers = useMemo(() => {
    const map = new Map<string, string>();
    for (const invoice of dueInvoices) {
      if (!map.has(invoice.customerId)) {
        map.set(invoice.customerId, invoice.customerName);
      }
    }
    return Array.from(map.entries()).map(([id, name]) => ({ id, name }));
  }, [dueInvoices]);

  useEffect(() => {
    setBankOptions(banks || []);
  }, [banks]);

  const banksById = useMemo(() => {
    const map = new Map<string, Bank | GeneralBank>();
    for (const bank of bankOptions || []) {
      if (!bank?.id) continue;
      map.set(String(bank.id), bank);
    }
    return map;
  }, [bankOptions]);

  const currenciesByCode = useMemo(() => {
    const map = new Map<string, Currency>();
    for (const currency of currencies || []) {
      if (!currency?.code) continue;
      map.set(String(currency.code).trim().toUpperCase(), currency);
    }
    return map;
  }, [currencies]);

  const selectedCustomerInvoices = useMemo(() => {
    if (!selectedCustomerId) return [];
    return dueInvoices
      .filter((invoice) => invoice.customerId === selectedCustomerId)
      .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
  }, [dueInvoices, selectedCustomerId]);

  const beneficiaryName = useMemo(() => {
    const selected = customers.find((entry) => entry.id === selectedCustomerId);
    return String(selected?.name || '').trim();
  }, [customers, selectedCustomerId]);

  const resetNewBankDraft = () => {
    setNewBankDraft({
      code: '',
      name: '',
      nameEn: '',
      branch: '',
    });
  };

  const handleCreateGeneralBank = async () => {
    const payload = {
      code: newBankDraft.code.trim(),
      name: newBankDraft.name.trim(),
      nameEn: newBankDraft.nameEn.trim() || newBankDraft.name.trim(),
      branch: newBankDraft.branch.trim() || undefined,
      isActive: true,
    };

    if (!payload.code || !payload.name) {
      toast({
        title: 'بيانات ناقصة',
        description: 'أدخل رمز البنك واسم البنك على الأقل.',
        variant: 'destructive',
      });
      return;
    }

    setIsCreatingBank(true);
    try {
      const response = await fetch('/api/general-banks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const result = await response.json().catch(() => null);
      if (!response.ok) {
        throw new Error(String(result?.error || 'Failed to create bank'));
      }

      const createdBank = result as GeneralBank;
      setBankOptions((prev) => [...prev, createdBank]);
      if (pendingBankRowIndex !== null) {
        setCheckRows((prev) => prev.map((item, itemIndex) => (
          itemIndex === pendingBankRowIndex
            ? {
                ...item,
                bankId: createdBank.id,
                bankName: String(createdBank.name || createdBank.nameEn || createdBank.code || ''),
              }
            : item
        )));
      }

      setIsAddBankDialogOpen(false);
      setPendingBankRowIndex(null);
      resetNewBankDraft();
      toast({
        title: 'تمت الإضافة',
        description: 'تمت إضافة البنك واختياره في الشيك الحالي.',
      });
    } catch (error) {
      toast({
        title: 'تعذر إضافة البنك',
        description: error instanceof Error ? error.message : 'حدث خطأ غير متوقع.',
        variant: 'destructive',
      });
    } finally {
      setIsCreatingBank(false);
    }
  };

  const paymentExchangeRateValue = useMemo(() => {
    const parsed = Number(exchangeRate || 0);
    if (currencyCode === defaultCurrencyCode) return 1;
    return Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
  }, [exchangeRate, currencyCode, defaultCurrencyCode]);

  const convertCheckAmountToPayment = (checkAmount: number, checkCurrencyCode?: string): number => {
    const normalizedCheckCurrency = String(checkCurrencyCode || currencyCode || defaultCurrencyCode).trim() || defaultCurrencyCode;
    if (!Number.isFinite(checkAmount) || checkAmount <= 0) return 0;
    if (normalizedCheckCurrency === currencyCode) return checkAmount;

    const sourceRateRaw = Number(currenciesByCode.get(normalizedCheckCurrency)?.exchangeRate || 0);
    const sourceRate = normalizedCheckCurrency === defaultCurrencyCode
      ? 1
      : (Number.isFinite(sourceRateRaw) && sourceRateRaw > 0 ? sourceRateRaw : 1);

    const amountInBase = normalizedCheckCurrency === defaultCurrencyCode
      ? checkAmount
      : checkAmount * sourceRate;

    return currencyCode === defaultCurrencyCode
      ? amountInBase
      : amountInBase / paymentExchangeRateValue;
  };

  const checksTotal = useMemo(() => {
    return checkRows.reduce((sum, row) => {
      const value = Number(row.amount || 0);
      if (!Number.isFinite(value) || value <= 0) return sum;
      return sum + convertCheckAmountToPayment(value, row.currency);
    }, 0);
  }, [checkRows, currencyCode, defaultCurrencyCode, paymentExchangeRateValue, currenciesByCode]);

  const convertInvoiceAmountToPayment = (invoice: SalesInvoice, invoiceAmount: number): number => {
    const invoiceCurrency = String(invoice.currencyCode || defaultCurrencyCode).trim() || defaultCurrencyCode;
    const invoiceRateRaw = Number(invoice.exchangeRate || 0);
    const invoiceRate = invoiceCurrency === defaultCurrencyCode
      ? 1
      : (Number.isFinite(invoiceRateRaw) && invoiceRateRaw > 0 ? invoiceRateRaw : 1);

    if (invoiceCurrency === currencyCode) return invoiceAmount;

    const baseAmount = invoiceCurrency === defaultCurrencyCode
      ? invoiceAmount
      : invoiceAmount * invoiceRate;

    return currencyCode === defaultCurrencyCode
      ? baseAmount
      : baseAmount / paymentExchangeRateValue;
  };

  const convertPaymentAmountToInvoice = (invoice: SalesInvoice, paymentAmount: number): number => {
    const invoiceCurrency = String(invoice.currencyCode || defaultCurrencyCode).trim() || defaultCurrencyCode;
    const invoiceRateRaw = Number(invoice.exchangeRate || 0);
    const invoiceRate = invoiceCurrency === defaultCurrencyCode
      ? 1
      : (Number.isFinite(invoiceRateRaw) && invoiceRateRaw > 0 ? invoiceRateRaw : 1);

    if (invoiceCurrency === currencyCode) return paymentAmount;

    const baseAmount = currencyCode === defaultCurrencyCode
      ? paymentAmount
      : paymentAmount * paymentExchangeRateValue;

    return invoiceCurrency === defaultCurrencyCode
      ? baseAmount
      : baseAmount / invoiceRate;
  };

  const allocatedTotalInPaymentCurrency = useMemo(() => {
    return selectedCustomerInvoices.reduce((sum, invoice) => {
      const allocationInInvoiceCurrency = Number(allocationDrafts[invoice.id] || 0);
      if (!Number.isFinite(allocationInInvoiceCurrency) || allocationInInvoiceCurrency <= 0) return sum;
      return sum + convertInvoiceAmountToPayment(invoice, allocationInInvoiceCurrency);
    }, 0);
  }, [allocationDrafts, selectedCustomerInvoices, currencyCode, defaultCurrencyCode, paymentExchangeRateValue]);

  const effectiveAmount = method === 'check' ? checksTotal : Number(amount || 0);
  const remainingToAllocate = Math.max(0, effectiveAmount - allocatedTotalInPaymentCurrency);
  const allocationDeltaInPaymentCurrency = effectiveAmount - allocatedTotalInPaymentCurrency;
  const amountInBaseCurrency = currencyCode !== defaultCurrencyCode
    ? effectiveAmount * paymentExchangeRateValue
    : null;

  const focusPaymentField = (step: 1 | -1, source: HTMLElement) => {
    const root = formNavRef.current;
    if (!root) return;
    const fields = Array.from(
      root.querySelectorAll<HTMLElement>('[data-payment-nav="true"]:not([disabled])')
    ).filter((el) => el.offsetParent !== null);
    if (fields.length === 0) return;
    const currentIndex = fields.findIndex((el) => el === source);
    if (currentIndex < 0) return;
    const nextIndex = currentIndex + step;
    if (nextIndex < 0 || nextIndex >= fields.length) return;
    fields[nextIndex].focus();
  };

  const handlePaymentFieldNavigation = (event: React.KeyboardEvent<HTMLElement>) => {
    const key = event.key;
    if (!['Enter', 'ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp'].includes(key)) return;

    const target = event.currentTarget as HTMLElement;
    if (target.getAttribute('role') === 'combobox' && target.getAttribute('aria-expanded') === 'true') {
      return;
    }

    if (key === 'Enter' || key === 'ArrowRight' || key === 'ArrowDown') {
      event.preventDefault();
      focusPaymentField(1, target);
      return;
    }

    if (key === 'ArrowLeft' || key === 'ArrowUp') {
      event.preventDefault();
      focusPaymentField(-1, target);
    }
  };

  const autoAllocate = () => {
    const total = method === 'check' ? checksTotal : Number(amount || 0);
    if (!Number.isFinite(total) || total <= 0) return;

    let remainingInPaymentCurrency = total;
    const nextDrafts: Record<string, string> = {};
    for (const invoice of selectedCustomerInvoices) {
      if (remainingInPaymentCurrency <= 0) {
        nextDrafts[invoice.id] = '0';
        continue;
      }
      const dueInInvoiceCurrency = Number(invoice.amountDue || 0);
      const dueInPaymentCurrency = convertInvoiceAmountToPayment(invoice, dueInInvoiceCurrency);
      const allocatedInPaymentCurrency = Math.min(remainingInPaymentCurrency, dueInPaymentCurrency);
      const allocatedInInvoiceCurrency = convertPaymentAmountToInvoice(invoice, allocatedInPaymentCurrency);
      nextDrafts[invoice.id] = allocatedInInvoiceCurrency.toFixed(2);
      remainingInPaymentCurrency -= allocatedInPaymentCurrency;
    }
    setAllocationDrafts(nextDrafts);
  };

  const allocateWithSorting = (invoices: typeof selectedCustomerInvoices) => {
    const total = method === 'check' ? checksTotal : Number(amount || 0);
    if (!Number.isFinite(total) || total <= 0) return;

    let remainingInPaymentCurrency = total;
    const nextDrafts: Record<string, string> = {};
    for (const invoice of invoices) {
      if (remainingInPaymentCurrency <= 0) {
        nextDrafts[invoice.id] = '0';
        continue;
      }
      const dueInInvoiceCurrency = Number(invoice.amountDue || 0);
      const dueInPaymentCurrency = convertInvoiceAmountToPayment(invoice, dueInInvoiceCurrency);
      const allocatedInPaymentCurrency = Math.min(remainingInPaymentCurrency, dueInPaymentCurrency);
      const allocatedInInvoiceCurrency = convertPaymentAmountToInvoice(invoice, allocatedInPaymentCurrency);
      nextDrafts[invoice.id] = allocatedInInvoiceCurrency.toFixed(2);
      remainingInPaymentCurrency -= allocatedInPaymentCurrency;
    }
    setAllocationDrafts(nextDrafts);
  };

  const allocateByOldestFirst = () => {
    const sorted = [...selectedCustomerInvoices].sort(
      (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()
    );
    allocateWithSorting(sorted);
  };

  const allocateByNewestFirst = () => {
    const sorted = [...selectedCustomerInvoices].sort(
      (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
    );
    allocateWithSorting(sorted);
  };

  const allocateBySameCurrencyOldest = () => {
    if (!currencyCode) return;
    const sameCurrency = selectedCustomerInvoices.filter(
      (inv) => String(inv.currencyCode || defaultCurrencyCode).toUpperCase() === String(currencyCode).toUpperCase()
    );
    const sorted = [...sameCurrency].sort(
      (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()
    );
    allocateWithSorting(sorted);
  };

  const allocateBySameCurrencyNewest = () => {
    if (!currencyCode) return;
    const sameCurrency = selectedCustomerInvoices.filter(
      (inv) => String(inv.currencyCode || defaultCurrencyCode).toUpperCase() === String(currencyCode).toUpperCase()
    );
    const sorted = [...sameCurrency].sort(
      (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
    );
    allocateWithSorting(sorted);
  };

  const selectAllInvoices = () => {
    const nextDrafts: Record<string, string> = {};
    for (const invoice of selectedCustomerInvoices) {
      nextDrafts[invoice.id] = String(Number(invoice.amountDue || 0).toFixed(2));
    }
    setAllocationDrafts(nextDrafts);
  };

  const selectSameCurrency = () => {
    if (!currencyCode) return;
    const nextDrafts: Record<string, string> = {};
    for (const invoice of selectedCustomerInvoices) {
      if (String(invoice.currencyCode || defaultCurrencyCode).toUpperCase() === String(currencyCode).toUpperCase()) {
        nextDrafts[invoice.id] = String(Number(invoice.amountDue || 0).toFixed(2));
      }
    }
    setAllocationDrafts(nextDrafts);
  };

  const deselectAll = () => {
    setAllocationDrafts({});
  };

  const totalDue = dueInvoices.reduce((sum, invoice) => sum + invoice.amountDue, 0);

  const recentPayments = useMemo(() => {
    return (payments || [])
      .slice()
      .sort((a, b) => new Date(String(b.date || 0)).getTime() - new Date(String(a.date || 0)).getTime())
      .slice(0, 20);
  }, [payments]);

  const filteredRecentPayments = useMemo(() => {
    const query = String(recentPaymentsSearch || '').trim().toLowerCase();
    if (!query) return recentPayments;
    return recentPayments.filter((payment) => {
      const technicalId = String(payment.id || '').toLowerCase();
      const shortOrSavedRef = resolveReceiptReference(payment).toLowerCase();
      const manualRef = String(payment.reference || '').toLowerCase();
      const customerIdText = String(payment.customerId || '').toLowerCase();
      const customerNameText = String(customerNamesById.get(String(payment.customerId || '')) || '').toLowerCase();
      return technicalId.includes(query)
        || shortOrSavedRef.includes(query)
        || manualRef.includes(query)
        || customerNameText.includes(query)
        || customerIdText.includes(query);
    });
  }, [customerNamesById, recentPayments, recentPaymentsSearch]);

  useEffect(() => {
    if (method !== 'check') return;
    setAmount(checksTotal > 0 ? checksTotal.toFixed(2) : '');
  }, [method, checksTotal]);

  useEffect(() => {
    const normalizedEditId = String(editPaymentId || '').trim();
    if (!normalizedEditId) return;
    const target = (payments || []).find((entry) => String(entry.id || '') === normalizedEditId);
    if (!target) return;

    setEditingPaymentId(normalizedEditId);
    setSelectedCustomerId(String(target.customerId || ''));
    setAmount(String(Number(target.amount || 0).toFixed(2)));
    setMethod((target.method as SalesInvoicePaymentMethod['method']) || 'cash');
    setCurrencyCode(String(target.currencyCode || defaultCurrencyCode));
    setExchangeRate(String(Number(target.exchangeRate || 1)));
    setRateDate(String(target.rateDate || target.date || '').slice(0, 10));
    setVoucherDate(String(target.date || '').slice(0, 10) || new Date().toISOString().slice(0, 10));
    setIsAdvance(Boolean(target.isAdvance));
    setReference(String(target.reference || ''));
    setNotes(String(target.notes || ''));

    const targetNotes = String(target.notes || '');
    const jsonMatch = targetNotes.match(/\[\[CHECKS_JSON\]\]([\s\S]*)$/);
    if (jsonMatch?.[1]) {
      try {
        const parsed = JSON.parse(jsonMatch[1]) as Array<{
          checkNumber?: string;
          bankId?: string;
          bankName?: string;
          checkDate?: string;
          amount?: number;
        }>;
        const restoredRows = (parsed || [])
          .map((row) => ({
            checkNumber: String(row.checkNumber || '').trim(),
            bankId: String(row.bankId || '').trim(),
            bankName: String(row.bankName || '').trim(),
            checkDate: String(row.checkDate || new Date().toISOString().slice(0, 10)).slice(0, 10),
            amount: Number(row.amount || 0) > 0 ? Number(row.amount).toFixed(2) : '',
            currency: String((row as any).currency || target.currencyCode || defaultCurrencyCode).trim() || defaultCurrencyCode,
            reference: String((row as any).reference || '').trim(),
            status: (String((row as any).status || 'pending').trim() as ReceiptCheckRow['status']) || 'pending',
          }))
          .filter((row) => row.checkNumber || row.bankName || Number(row.amount || 0) > 0);
        setCheckRows(restoredRows.length > 0 ? restoredRows : [createEmptyCheckRow(String(target.currencyCode || defaultCurrencyCode))]);
      } catch {
        setCheckRows([createEmptyCheckRow(String(target.currencyCode || defaultCurrencyCode))]);
      }
    } else {
      const checkNumberMatch = targetNotes.match(/رقم الشيك:\s*([^|\n]+)/);
      const checkBankMatch = targetNotes.match(/البنك:\s*([^|\n]+)/);
      const checkDateMatch = targetNotes.match(/تاريخ الشيك:\s*([^|\n]+)/);
      const fallbackCheckNumber = String((checkNumberMatch?.[1] || target.reference || '')).trim();
      const fallbackBankName = String(checkBankMatch?.[1] || '').trim();
      const fallbackBankByName = (banks || []).find(
        (entry) => String(entry.name || '').trim().toLowerCase() === fallbackBankName.toLowerCase()
      );
      const fallbackCheckDate = String(checkDateMatch?.[1] || target.date || new Date().toISOString().slice(0, 10)).trim().slice(0, 10);

      if (fallbackCheckNumber || fallbackBankName) {
        setCheckRows([
          {
            checkNumber: fallbackCheckNumber,
            bankId: String(fallbackBankByName?.id || ''),
            bankName: fallbackBankName,
            checkDate: fallbackCheckDate,
            amount: Number(target.amount || 0) > 0 ? Number(target.amount).toFixed(2) : '',
            currency: String(target.currencyCode || defaultCurrencyCode).trim() || defaultCurrencyCode,
            reference: String(target.reference || '').trim(),
            status: 'pending',
          },
        ]);
      } else {
        setCheckRows([createEmptyCheckRow(String(target.currencyCode || defaultCurrencyCode))]);
      }
    }

    const nextAllocations: Record<string, string> = {};
    (target.allocations || []).forEach((row) => {
      if (row?.invoiceId && Number(row.amount || 0) > 0) {
        nextAllocations[String(row.invoiceId)] = Number(row.amount).toFixed(2);
      }
    });
    setAllocationDrafts(nextAllocations);
  }, [editPaymentId, payments, defaultCurrencyCode, banks]);

  const onCancelReceipt = async (payment: CustomerPayment) => {
    if (!payment?.id) return;
    try {
      setIsCancellingId(payment.id);
      const result = await handleCancelSalesPaymentReceipt(
        payment.id,
        'Cancelled from sales payment received screen',
        userName,
        userId
      );

      if (!result.success) {
        toast({
          title: 'تعذر إلغاء السند',
          description: result.error || 'حدث خطأ غير متوقع.',
          variant: 'destructive',
        });
        return;
      }

      toast({
        title: 'تم إلغاء السند',
        description: `تم إلغاء سند القبض ${payment.id} بنجاح.`,
      });
      router.refresh();
    } catch {
      toast({
        title: 'تعذر إلغاء السند',
        description: 'حدث خطأ غير متوقع أثناء إلغاء السند.',
        variant: 'destructive',
      });
    } finally {
      setIsCancellingId('');
    }
  };

  const onRecordPayment = async () => {
    if (isEditLocked) {
      return;
    }

    const parsedAmount = Number(amount);

    let customerId = '';
    let allocations: Array<{ invoiceId: string; amount: number }> = [];

    let normalizedChecks: Array<{
      checkNumber: string;
      bankId?: string;
      bankName: string;
      checkDate: string;
      amount: number;
    }> = [];

    if (!selectedCustomerId) {
      toast({ title: 'خطأ', description: 'يرجى اختيار الزبون/المستفيد.', variant: 'destructive' });
      return;
    }
    customerId = selectedCustomerId;
    allocations = selectedCustomerInvoices
      .map((invoice) => ({
        invoiceId: invoice.id,
        amount: Number(allocationDrafts[invoice.id] || 0),
      }))
      .filter((entry) => Number.isFinite(entry.amount) && entry.amount > 0);

    if (allocations.length === 0) {
      toast({ title: 'خطأ', description: 'يرجى إدخال تخصيص واحد على الأقل.', variant: 'destructive' });
      return;
    }

    const paymentAmount = method === 'check' ? checksTotal : parsedAmount;
    if (!Number.isFinite(paymentAmount) || paymentAmount <= 0) {
      toast({
        title: 'خطأ',
        description: 'يرجى إدخال مبلغ دفع صحيح أكبر من صفر.',
        variant: 'destructive',
      });
      return;
    }

    const totalAllocatedInPayment = allocations.reduce((sum, entry) => {
      const invoice = selectedCustomerInvoices.find((row) => row.id === entry.invoiceId);
      if (!invoice) return sum;
      return sum + convertInvoiceAmountToPayment(invoice, entry.amount);
    }, 0);
    if (Math.abs(totalAllocatedInPayment - paymentAmount) > 0.01) {
      toast({
        title: 'خطأ',
        description: 'مجموع التخصيصات بعد التحويل يجب أن يساوي مبلغ الدفعة.',
        variant: 'destructive',
      });
      return;
    }

    for (const entry of allocations) {
      const invoice = selectedCustomerInvoices.find((row) => row.id === entry.invoiceId);
      if (!invoice) continue;
      if (entry.amount - Number(invoice.amountDue || 0) > 0.01) {
        toast({
          title: 'خطأ',
          description: `التخصيص أكبر من المتبقي للفاتورة ${invoice.invoiceNumber}.`,
          variant: 'destructive',
        });
        return;
      }
    }

    if (method === 'check') {
      const materialRows = checkRows.filter((row) =>
        String(row.checkNumber || '').trim() ||
        String(row.bankId || '').trim() ||
        String(row.bankName || '').trim() ||
        String(row.checkDate || '').trim() ||
        String(row.reference || '').trim() ||
        Number(row.amount || 0) > 0
      );

      if (materialRows.length === 0) {
        toast({
          title: 'خطأ',
          description: 'يرجى إدخال شيك واحد على الأقل.',
          variant: 'destructive',
        });
        return;
      }

      for (const row of materialRows) {
        const rowAmount = Number(row.amount || 0);
        if (!String(row.checkNumber || '').trim()) {
          toast({
            title: 'خطأ',
            description: 'يرجى إدخال رقم الشيك لكل سطر.',
            variant: 'destructive',
          });
          return;
        }
        if (banks.length > 0 && !String(row.bankId || '').trim()) {
          toast({
            title: 'خطأ',
            description: 'يرجى اختيار البنك لكل سطر شيك.',
            variant: 'destructive',
          });
          return;
        }
        if (!String(row.bankName || '').trim()) {
          toast({
            title: 'خطأ',
            description: 'يرجى إدخال اسم البنك لكل سطر.',
            variant: 'destructive',
          });
          return;
        }
        if (!String(row.checkDate || '').trim()) {
          toast({
            title: 'خطأ',
            description: 'يرجى إدخال تاريخ الشيك لكل سطر.',
            variant: 'destructive',
          });
          return;
        }
        if (!Number.isFinite(rowAmount) || rowAmount <= 0) {
          toast({
            title: 'خطأ',
            description: 'يرجى إدخال مبلغ صحيح لكل شيك.',
            variant: 'destructive',
          });
          return;
        }
        if (!String(row.currency || '').trim()) {
          toast({
            title: 'خطأ',
            description: 'يرجى اختيار العملة لكل شيك.',
            variant: 'destructive',
          });
          return;
        }
      }

      normalizedChecks = materialRows.map((row) => {
        const selectedBank = banksById.get(String(row.bankId || '').trim());
        const autoBankName = selectedBank
          ? String(selectedBank.name || (selectedBank as any).fullName || selectedBank.nameEn || selectedBank.code || selectedBank.id)
          : '';
        const normalizedBankName = String(row.bankName || autoBankName).trim();

        return {
          checkNumber: String(row.checkNumber || '').trim(),
          bankId: String(row.bankId || '').trim() || undefined,
          bankName: normalizedBankName,
          checkDate: String(row.checkDate || '').trim().slice(0, 10),
          amount: Number(row.amount || 0),
          currency: String(row.currency || currencyCode || defaultCurrencyCode).trim() || defaultCurrencyCode,
          reference: String(row.reference || '').trim() || undefined,
          status: (String(row.status || 'pending').trim() as ReceiptCheckRow['status']) || 'pending',
        };
      });

      const summed = normalizedChecks.reduce((sum, row) => sum + convertCheckAmountToPayment(row.amount, (row as any).currency), 0);
      const totalAllocatedInPayment = allocations.reduce((sum, entry) => {
        const invoice = selectedCustomerInvoices.find((row) => row.id === entry.invoiceId);
        if (!invoice) return sum;
        return sum + convertInvoiceAmountToPayment(invoice, entry.amount);
      }, 0);
      if (Math.abs(totalAllocatedInPayment - summed) > 0.01) {
        toast({
          title: 'خطأ',
          description: 'مجموع الشيكات يجب أن يساوي مجموع التخصيصات بعد التحويل.',
          variant: 'destructive',
        });
        return;
      }

      setAmount(summed.toFixed(2));
    }

    const checkMetadata = method === 'check'
      ? normalizedChecks
          .map((row, index) => `شيك ${index + 1}: ${row.checkNumber} | ${row.bankName} | ${row.checkDate} | ${row.amount.toFixed(2)} ${String((row as any).currency || currencyCode)} | ${String((row as any).status || 'pending')} | ${String((row as any).reference || '-')}`)
          .join('\n')
      : '';

    const checksJsonMarker = method === 'check'
      ? `[[CHECKS_JSON]]${JSON.stringify(normalizedChecks)}`
      : '';

    const finalReference = method === 'check'
      ? (String(reference || '').trim() || String((normalizedChecks[0] as any)?.reference || '').trim() || String(normalizedChecks[0]?.checkNumber || '').trim() || undefined)
      : (String(reference || '').trim() || undefined);

    const finalNotes = [String(notes || '').trim(), checkMetadata, checksJsonMarker]
      .filter((entry) => entry.length > 0)
      .join('\n') || undefined;

    try {
      setIsSubmitting(true);

      const basePayload = {
        amount: method === 'check' ? checksTotal : parsedAmount,
        method,
        receiptChecks: method === 'check' ? normalizedChecks : undefined,
        date: voucherDate,
        currencyCode,
        exchangeRate: Number(exchangeRate || 0),
        rateDate,
        isAdvance,
        postingStatus,
        reference: finalReference,
        notes: finalNotes,
        allocations,
        userId,
        userName,
      };

      const result = editingPaymentId
        ? await handleUpdateSalesPaymentReceipt({
            paymentId: editingPaymentId,
            ...basePayload,
          })
        : await handleCreateSalesPaymentReceipt({
            customerId,
            ...basePayload,
          });

      if (!result.success) {
        toast({
          title: 'تعذر تسجيل الدفعة',
          description: result.error || 'حدث خطأ غير متوقع.',
          variant: 'destructive',
        });
        return;
      }

      toast({
        title: editingPaymentId ? 'تم تعديل السند' : 'تم تسجيل الدفعة',
        description: editingPaymentId
          ? 'تم تحديث السند المرحل/الفعّال حسب السياسات المعتمدة.'
          : 'تم ترحيل سند القبض وتحديث الفواتير المخصصة.',
      });

      setAmount('');
      setReference('');
      setNotes('');
      setVoucherDate(new Date().toISOString().slice(0, 10));
      setCheckRows([createEmptyCheckRow(currencyCode)]);
      setAllocationDrafts({});
      setEditingPaymentId('');
      router.replace('/admin/sales/payment/received');
      router.refresh();
    } catch {
      toast({
        title: 'تعذر تسجيل الدفعة',
        description: 'حدث خطأ غير متوقع أثناء تسجيل الدفعة.',
        variant: 'destructive',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-4">
      <Tabs defaultValue="create" dir="rtl" className="space-y-4">
        <TabsList className="flex h-auto w-full flex-wrap justify-start gap-1 rounded-lg border bg-muted/40 p-1">
          <TabsTrigger value="create" className="text-xs sm:text-sm">إنشاء دفعة</TabsTrigger>
          <TabsTrigger value="recent" className="text-xs sm:text-sm">آخر سندات القبض</TabsTrigger>
        </TabsList>

        <TabsContent value="create" className="mt-0">
          <Card>
            <CardHeader>
              <CardTitle>إنشاء دفعة</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
          {editingPaymentId && (
            <div className="rounded-md border border-amber-300 bg-amber-50 px-4 py-3 flex items-center justify-between">
              <p className="text-sm font-medium">وضع تعديل سند قبض: {editingPaymentId}</p>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => {
                  setEditingPaymentId('');
                  setAmount('');
                  setReference('');
                  setNotes('');
                  setVoucherDate(new Date().toISOString().slice(0, 10));
                  setCheckRows([createEmptyCheckRow(currencyCode)]);
                  setAllocationDrafts({});
                  router.replace('/admin/sales/payment/received');
                }}
              >
                إلغاء التعديل
              </Button>
            </div>
          )}

          {editingPaymentId && <DocumentLockBanner lockStatus={lockStatus} />}

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">فواتير مستحقة</p>
              <p className="text-2xl font-bold">{dueInvoices.length}</p>
            </div>
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">إجمالي المستحق</p>
              <p className="text-2xl font-bold">{totalDue.toFixed(2)}</p>
            </div>
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">إجراء سريع</p>
              <Button asChild className="mt-2 w-full" variant="outline">
                <Link href="/admin/sales/history">عرض كامل السجل</Link>
              </Button>
            </div>
          </div>

          <div className="rounded-lg border bg-muted/30 p-3">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
              <div className="space-y-1">
                <label className="text-sm font-medium">مرجع السند (مختصر)</label>
                <Input value={shortReceiptReference} readOnly className="h-9 bg-background max-w-xs font-mono" />
              </div>
              <div className="space-y-1">
                <label className="text-sm font-medium">المعرّف التقني</label>
                <Input
                  value={editingPaymentId || 'سيظهر بعد الحفظ'}
                  readOnly
                  className="h-9 bg-background max-w-xs font-mono text-xs"
                  title={editingPaymentId || 'سيظهر بعد الحفظ'}
                />
              </div>
              <div className="space-y-1">
                <label className="text-sm font-medium">تاريخ السند</label>
                <Input
                  type="date"
                  lang="en"
                  dir="ltr"
                  value={voucherDate}
                  onChange={(event) => setVoucherDate(event.target.value)}
                  className="h-9 bg-background max-w-[180px]"
                />
              </div>
              <div className="space-y-1">
                <label className="text-sm font-medium">اسم المستفيد</label>
                <Select
                  value={selectedCustomerId}
                  onValueChange={(value) => {
                    setSelectedCustomerId(value);
                    setAllocationDrafts({});
                    setAmount('');
                  }}
                >
                  <SelectTrigger className="h-9 bg-background" data-payment-nav="true" onKeyDown={handlePaymentFieldNavigation}>
                    <SelectValue placeholder="اختر المستفيد" />
                  </SelectTrigger>
                  <SelectContent>
                    {customers.map((customer) => (
                      <SelectItem key={customer.id} value={customer.id}>
                        {customer.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>

          <div ref={formNavRef} className="rounded-lg border p-3">
          <div className="overflow-x-auto">
          <div className="flex items-end gap-3 min-w-max pb-1">
            <div className="space-y-2 min-w-[260px]">
              <label className="text-sm font-medium">العميل</label>
              <Input value={beneficiaryName || 'اختر المستفيد من أعلى'} readOnly className="bg-background" />
            </div>

            <div className="space-y-2 min-w-[180px]">
              <label className="text-sm font-medium">طريقة الدفع</label>
              <Select
                value={method}
                onValueChange={(value) => setMethod(value as SalesInvoicePaymentMethod['method'])}
              >
                <SelectTrigger data-payment-nav="true" onKeyDown={handlePaymentFieldNavigation}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {PAYMENT_METHODS.map((paymentMethod) => (
                    <SelectItem key={paymentMethod} value={paymentMethod}>
                      {PAYMENT_METHOD_LABELS[paymentMethod]}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2 min-w-[180px]">
              <label className="text-sm font-medium">العملة</label>
              <Select
                value={currencyCode}
                onValueChange={(value) => {
                  const nextCode = String(value || '').trim();
                  setCurrencyCode(nextCode);

                  if (nextCode === defaultCurrencyCode) {
                    setExchangeRate('1');
                    return;
                  }

                  const selectedCurrency = currenciesByCode.get(nextCode.toUpperCase());
                  const suggestedRate = Number((selectedCurrency as any)?.exchangeRate || 0);
                  if (Number.isFinite(suggestedRate) && suggestedRate > 0) {
                    setExchangeRate(String(suggestedRate));
                  }
                }}
              >
                <SelectTrigger data-payment-nav="true" onKeyDown={handlePaymentFieldNavigation}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {currencies.map((currency) => (
                    <SelectItem key={currency.code} value={currency.code}>
                      {currency.code} - {currency.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2 min-w-[180px]">
              <label className="text-sm font-medium">سعر الصرف (مقابل {defaultCurrencyCode})</label>
              <Input
                type="number"
                lang="en"
                dir="ltr"
                inputMode="decimal"
                min="0"
                step="0.0001"
                value={exchangeRate}
                onChange={(event) => setExchangeRate(event.target.value)}
                placeholder="1"
                data-payment-nav="true"
                onKeyDown={handlePaymentFieldNavigation}
              />
            </div>

            <div className="space-y-2 min-w-[170px]">
              <label className="text-sm font-medium">تاريخ السعر</label>
              <Input
                type="date"
                lang="en"
                dir="ltr"
                value={rateDate}
                onChange={(event) => setRateDate(event.target.value)}
                data-payment-nav="true"
                onKeyDown={handlePaymentFieldNavigation}
              />
            </div>

            <div className="space-y-2 min-w-[180px]">
              <label className="text-sm font-medium">المبلغ</label>
              <Input
                type="number"
                lang="en"
                dir="ltr"
                inputMode="decimal"
                min="0"
                step="0.01"
                value={amount}
                onChange={(event) => setAmount(event.target.value)}
                placeholder="0.00"
                disabled={method === 'check'}
                className="max-w-[220px]"
                data-payment-nav="true"
                onKeyDown={handlePaymentFieldNavigation}
              />
              {selectedCustomerId ? (
                <p className="text-xs text-muted-foreground">
                  غير مخصص بعد (بعملة السند): {remainingToAllocate.toFixed(2)}
                </p>
              ) : null}
              {method === 'check' && (
                <p className="text-xs text-muted-foreground">يتم احتساب المبلغ تلقائيًا من مجموع الشيكات.</p>
              )}
            </div>

            {amountInBaseCurrency !== null && (
              <div className="space-y-2 min-w-[170px]">
                <label className="text-sm font-medium">القيمة بـ {defaultCurrencyCode}</label>
                <Input
                  type="number"
                  lang="en"
                  dir="ltr"
                  inputMode="decimal"
                  readOnly
                  tabIndex={-1}
                  value={amountInBaseCurrency.toFixed(2)}
                  className="bg-muted cursor-default"
                />
              </div>
            )}

            <div className="space-y-2 min-w-[220px]">
              <label className="text-sm font-medium">مرجع الدفع (اختياري)</label>
              <Input
                value={reference}
                onChange={(event) => setReference(event.target.value)}
                placeholder="رقم الشيك / مرجع التحويل"
                className="max-w-sm"
                data-payment-nav="true"
                onKeyDown={handlePaymentFieldNavigation}
              />
            </div>

            <div className="space-y-2 min-w-[150px]">
              <label className="text-sm font-medium">دفعة مقدمة</label>
              <Select value={isAdvance ? 'yes' : 'no'} onValueChange={(value) => setIsAdvance(value === 'yes')}>
                <SelectTrigger data-payment-nav="true" onKeyDown={handlePaymentFieldNavigation}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="no">لا</SelectItem>
                  <SelectItem value="yes">نعم</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          </div>

            {method === 'check' && (
              <div className="mt-3 space-y-3 rounded-md border p-3 bg-green-50">
                  <div className="flex items-center justify-between">
                    <label className="text-sm font-medium">تفاصيل الشيكات</label>
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => setCheckRows((prev) => [...prev, createEmptyCheckRow(currencyCode)])}
                    >
                      إضافة شيك
                    </Button>
                  </div>
                  <div className="rounded-md border overflow-x-auto bg-background">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>رقم الشيك</TableHead>
                          <TableHead>تاريخ الشيك</TableHead>
                          <TableHead>البنك</TableHead>
                          <TableHead>اسم البنك</TableHead>
                          <TableHead className="text-right">المبلغ</TableHead>
                          <TableHead>العملة</TableHead>
                          <TableHead>المرجع</TableHead>
                          <TableHead>الحالة</TableHead>
                          <TableHead className="text-right">إجراء</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {checkRows.map((row, index) => (
                          <TableRow key={`check-row-${index + 1}`}>
                            <TableCell className="min-w-[150px] align-top">
                              <Input
                                value={row.checkNumber}
                                onChange={(event) => {
                                  const value = event.target.value;
                                  setCheckRows((prev) => prev.map((item, itemIndex) => (itemIndex === index ? { ...item, checkNumber: value } : item)));
                                }}
                                placeholder="رقم الشيك"
                              />
                            </TableCell>
                            <TableCell className="min-w-[140px] align-top">
                              <Input
                                type="date"
                                lang="en"
                                dir="ltr"
                                value={row.checkDate}
                                onChange={(event) => {
                                  const value = event.target.value;
                                  setCheckRows((prev) => prev.map((item, itemIndex) => (itemIndex === index ? { ...item, checkDate: value } : item)));
                                }}
                              />
                            </TableCell>
                            <TableCell className="min-w-[150px] align-top">
                              <Select
                                value={row.bankId || ''}
                                onValueChange={(value) => {
                                  if (value === '__add_new_bank__') {
                                    setPendingBankRowIndex(index);
                                    setIsAddBankDialogOpen(true);
                                    return;
                                  }

                                  const selected = banksById.get(String(value));
                                  const bankName = String(selected?.name || (selected as any)?.fullName || selected?.nameEn || selected?.code || value);
                                  setCheckRows((prev) => prev.map((item, itemIndex) => (
                                    itemIndex === index ? { ...item, bankId: value, bankName } : item
                                  )));
                                }}
                              >
                                <SelectTrigger>
                                  <SelectValue placeholder="البنك" />
                                </SelectTrigger>
                                <SelectContent>
                                  {bankOptions.map((bank) => (
                                    <SelectItem key={bank.id} value={bank.id}>
                                      {bank.name}
                                    </SelectItem>
                                  ))}
                                  <SelectItem value="__add_new_bank__">+ إضافة بنك جديد</SelectItem>
                                </SelectContent>
                              </Select>
                            </TableCell>
                            <TableCell className="min-w-[150px] align-top">
                              <Input
                                value={row.bankName}
                                onChange={(event) => {
                                  const value = event.target.value;
                                  setCheckRows((prev) => prev.map((item, itemIndex) => (itemIndex === index ? { ...item, bankName: value } : item)));
                                }}
                                placeholder="اسم البنك"
                              />
                            </TableCell>
                            <TableCell className="min-w-[130px] align-top">
                              <Input
                                type="text"
                                lang="en"
                                dir="ltr"
                                inputMode="decimal"
                                className="font-mono text-right"
                                value={row.amount}
                                onChange={(event) => {
                                  const value = event.target.value;
                                  setCheckRows((prev) => prev.map((item, itemIndex) => (itemIndex === index ? { ...item, amount: value } : item)));
                                }}
                                placeholder="0.00"
                              />
                            </TableCell>
                            <TableCell className="min-w-[130px] align-top">
                              <Select
                                value={row.currency || currencyCode}
                                onValueChange={(value) => {
                                  setCheckRows((prev) => prev.map((item, itemIndex) => (itemIndex === index ? { ...item, currency: value } : item)));
                                }}
                              >
                                <SelectTrigger>
                                  <SelectValue placeholder="العملة" />
                                </SelectTrigger>
                                <SelectContent>
                                  {currencies.map((currency) => (
                                    <SelectItem key={currency.code} value={currency.code}>{currency.code}</SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </TableCell>
                            <TableCell className="min-w-[160px] align-top">
                              <Input
                                value={row.reference}
                                onChange={(event) => {
                                  const value = event.target.value;
                                  setCheckRows((prev) => prev.map((item, itemIndex) => (itemIndex === index ? { ...item, reference: value } : item)));
                                }}
                                placeholder="مرجع / إيداع"
                              />
                            </TableCell>
                            <TableCell className="min-w-[140px] align-top">
                              <Select
                                value={row.status || 'pending'}
                                onValueChange={(value) => {
                                  setCheckRows((prev) => prev.map((item, itemIndex) => (itemIndex === index ? { ...item, status: value as ReceiptCheckRow['status'] } : item)));
                                }}
                              >
                                <SelectTrigger>
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="pending">قيد الانتظار</SelectItem>
                                  <SelectItem value="cleared">تم التصفية</SelectItem>
                                  <SelectItem value="rejected">مرفوض</SelectItem>
                                  <SelectItem value="returned">مرتجع</SelectItem>
                                </SelectContent>
                              </Select>
                            </TableCell>
                            <TableCell className="w-[80px] align-top text-right">
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                disabled={checkRows.length <= 1}
                                onClick={() => setCheckRows((prev) => (prev.length <= 1 ? prev : prev.filter((_, itemIndex) => itemIndex !== index)))}
                              >
                                <Trash2 className="h-4 w-4 text-destructive" />
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                  <div className="text-xs text-muted-foreground">
                    مجموع الشيكات (بعملة السند): <span className="font-mono" dir="ltr">{checksTotal.toFixed(2)}</span>
                  </div>
                </div>
            )}

            <div className="mt-3 space-y-2">
              <label className="text-sm font-medium">ملاحظات (اختياري)</label>
              <Input
                value={notes}
                onChange={(event) => setNotes(event.target.value)}
                placeholder="أي تفاصيل إضافية عن سند القبض"
                className="w-full max-w-2xl"
                data-payment-nav="true"
                onKeyDown={handlePaymentFieldNavigation}
              />
              {selectedCustomerId && (
                <p className={`text-xs ${Math.abs(allocationDeltaInPaymentCurrency) <= 0.01 ? 'text-emerald-600' : 'text-amber-600'}`}>
                  فرق التخصيص الحالي (بعملة السند): {allocationDeltaInPaymentCurrency.toFixed(2)}
                </p>
              )}
            </div>
          </div>

            {selectedCustomerId && selectedCustomerInvoices.length > 0 && (
            <div className="space-y-3 rounded-md border p-4">
              <div className="flex items-center justify-between">
                <p className="text-sm font-medium">تخصيص الدفعة على الفواتير</p>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button type="button" variant="outline" size="sm" className="gap-2">
                      توزيع تلقائي
                      <ChevronDown className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end" className="w-56">
                    <DropdownMenuItem onClick={autoAllocate}>
                      توزيع تلقائي
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => setAllocationDrafts({})}>
                      توزيع يدوي
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={allocateByOldestFirst}>
                      الأقدم أولاً
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={allocateByNewestFirst}>
                      الأحدث أولاً
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={allocateBySameCurrencyOldest}>
                      نفس العملة - الأقدم أولاً
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={allocateBySameCurrencyNewest}>
                      نفس العملة - الأحدث أولاً
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={selectAllInvoices}>
                      تحديد كل الفواتير
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={selectSameCurrency}>
                      تحديد نفس العملة
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={deselectAll}>
                      إلغاء التحديد
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
              <div className="rounded-md border overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الفاتورة</TableHead>
                      <TableHead>التاريخ</TableHead>
                      <TableHead className="text-end">المتبقي (عملة الفاتورة)</TableHead>
                      <TableHead className="text-end">التخصيص (عملة الفاتورة)</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selectedCustomerInvoices.map((invoice) => (
                      <TableRow key={invoice.id}>
                        <TableCell className="font-medium">{invoice.invoiceNumber}</TableCell>
                        <TableCell>{formatDateStable(invoice.date)}</TableCell>
                        <TableCell className="text-end font-mono" dir="ltr">{invoice.amountDue.toFixed(2)}</TableCell>
                        <TableCell className="text-end">
                          <Input
                            type="number"
                            lang="en"
                            dir="ltr"
                            inputMode="decimal"
                            min="0"
                            step="0.01"
                            value={allocationDrafts[invoice.id] || ''}
                            onChange={(event) => {
                              setAllocationDrafts((prev) => ({
                                ...prev,
                                [invoice.id]: event.target.value,
                              }));
                            }}
                            className="w-32 ms-auto"
                          />
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">المخصص (بعملة السند)</span>
                <span className="font-mono" dir="ltr">{allocatedTotalInPaymentCurrency.toFixed(2)} من {effectiveAmount.toFixed(2)}</span>
              </div>
            </div>
          )}

          <div className="flex justify-end">
            <Button
              disabled={isSubmitting || dueInvoices.length === 0 || isEditLocked}
              onClick={onRecordPayment}
              data-payment-nav="true"
              onKeyDown={handlePaymentFieldNavigation}
            >
              {isSubmitting ? (editingPaymentId ? 'جارٍ حفظ التعديل...' : 'جاري التسجيل...') : (editingPaymentId ? 'حفظ التعديل' : 'تسجيل الدفعة')}
            </Button>
          </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="recent" className="mt-0">
          <Card>
            <CardHeader>
              <CardTitle>آخر سندات القبض</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="mb-3">
                <Input
                  value={recentPaymentsSearch}
                  onChange={(event) => setRecentPaymentsSearch(event.target.value)}
                  placeholder="بحث برقم السند المختصر أو المعرّف التقني أو مرجع الدفع"
                  className="max-w-md"
                />
              </div>
              <div className="rounded-md border overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>السند</TableHead>
                      <TableHead>التاريخ</TableHead>
                      <TableHead>العميل</TableHead>
                      <TableHead>العملة</TableHead>
                      <TableHead>المبلغ</TableHead>
                      <TableHead>الحالة</TableHead>
                      <TableHead>الترحيل</TableHead>
                      <TableHead>إجراء</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredRecentPayments.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                          لا توجد نتائج مطابقة.
                        </TableCell>
                      </TableRow>
                    ) : (
                      filteredRecentPayments.map((payment) => {
                        const canCancel = payment.status !== 'cancelled';
                        const shortPaymentRef = resolveReceiptReference(payment);
                        const customerName = String(customerNamesById.get(String(payment.customerId || '')) || payment.customerId || '-');
                        return (
                          <TableRow key={payment.id}>
                            <TableCell className="font-medium">
                              <div className="flex flex-col">
                                <span className="font-mono" dir="ltr">{shortPaymentRef}</span>
                                <span className="text-[11px] text-muted-foreground font-mono" dir="ltr" title={payment.id}>
                                  {String(payment.id || '').slice(0, 22)}{String(payment.id || '').length > 22 ? '...' : ''}
                                </span>
                              </div>
                            </TableCell>
                            <TableCell>{formatDateStable(payment.date)}</TableCell>
                            <TableCell>{customerName}</TableCell>
                            <TableCell>{payment.currencyCode || defaultCurrencyCode}</TableCell>
                            <TableCell className="font-mono" dir="ltr">{Number(payment.amount || 0).toFixed(2)}</TableCell>
                            <TableCell>{payment.status === 'cancelled' ? 'ملغي' : 'فعال'}</TableCell>
                            <TableCell>{payment.postingStatus || 'posted'}</TableCell>
                            <TableCell>
                              <div className="flex items-center gap-2">
                                <Button
                                  asChild
                                  type="button"
                                  size="sm"
                                  variant="outline"
                                  disabled={payment.status === 'cancelled'}
                                >
                                  <Link href={`/admin/sales/payment/received/edit/${payment.id}`}>تعديل</Link>
                                </Button>
                                <Button
                                  type="button"
                                  size="sm"
                                  variant="outline"
                                  disabled={!canCancel || isCancellingId === payment.id}
                                  onClick={() => onCancelReceipt(payment)}
                                >
                                  {isCancellingId === payment.id ? 'جارٍ الإلغاء...' : 'إلغاء'}
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        );
                      })
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      <Dialog
        open={isAddBankDialogOpen}
        onOpenChange={(open) => {
          setIsAddBankDialogOpen(open);
          if (!open) {
            setPendingBankRowIndex(null);
            resetNewBankDraft();
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>إضافة بنك جديد</DialogTitle>
            <DialogDescription className="sr-only">أدخل بيانات البنك الجديد لإضافته إلى القائمة.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">رمز البنك</label>
              <Input
                value={newBankDraft.code}
                onChange={(event) => setNewBankDraft((prev) => ({ ...prev, code: event.target.value }))}
                placeholder="مثال: BOJ"
              />
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">اسم البنك</label>
              <Input
                value={newBankDraft.name}
                onChange={(event) => setNewBankDraft((prev) => ({ ...prev, name: event.target.value }))}
                placeholder="اسم البنك بالعربية"
              />
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">الاسم الإنجليزي</label>
              <Input
                value={newBankDraft.nameEn}
                onChange={(event) => setNewBankDraft((prev) => ({ ...prev, nameEn: event.target.value }))}
                placeholder="Bank name in English"
              />
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">الفرع</label>
              <Input
                value={newBankDraft.branch}
                onChange={(event) => setNewBankDraft((prev) => ({ ...prev, branch: event.target.value }))}
                placeholder="اختياري"
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setIsAddBankDialogOpen(false);
                setPendingBankRowIndex(null);
                resetNewBankDraft();
              }}
            >
              إلغاء
            </Button>
            <Button type="button" onClick={handleCreateGeneralBank} disabled={isCreatingBank}>
              {isCreatingBank ? 'جارٍ الحفظ...' : 'حفظ البنك'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Card>
        <CardHeader>
          <CardTitle>الفواتير المستحقة</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>الفاتورة</TableHead>
                  <TableHead>العميل</TableHead>
                  <TableHead>التاريخ</TableHead>
                  <TableHead>الإجمالي</TableHead>
                  <TableHead>المدفوع</TableHead>
                  <TableHead>المتبقي</TableHead>
                  <TableHead>إجراء</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {dueInvoices.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                      لا توجد فواتير مستحقة حاليًا.
                    </TableCell>
                  </TableRow>
                ) : (
                  dueInvoices.map((invoice) => (
                    <TableRow key={invoice.id}>
                      <TableCell className="font-medium">{invoice.invoiceNumber}</TableCell>
                      <TableCell>{invoice.customerName}</TableCell>
                      <TableCell>{formatDateStable(invoice.date)}</TableCell>
                      <TableCell>{invoice.grandTotal.toFixed(2)}</TableCell>
                      <TableCell>{invoice.amountReceived.toFixed(2)}</TableCell>
                      <TableCell className="font-semibold text-red-600">
                        {invoice.amountDue.toFixed(2)}
                      </TableCell>
                      <TableCell>
                        <Button asChild size="sm" variant="outline">
                          <Link href={`/admin/sales/view/${invoice.id}`}>عرض</Link>
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
