'use client';

import { useState, useTransition, useMemo, useEffect, Fragment } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { format } from 'date-fns';

import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { 
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Loader2, X, Check, ChevronsUpDown, Pencil, Eye, ListTree, ChevronDown, RefreshCw } from 'lucide-react';
import { Plus } from 'lucide-react';
import { type Supplier, type Customer, type Bank, type Currency, type PurchaseOrder, type SupplierPayment, type IncomingCheck } from '@/lib/types';
import { useToast } from '@/hooks/use-toast';
import { handleSupplierPayment, handleUpdateSupplierPaymentFull, handleCancelSupplierPayment, handleAcquireSupplierPaymentLock, handleReleaseSupplierPaymentLock, handleGetSupplierPaymentLocksStatus } from '@/lib/actions';
import { cn } from '@/lib/utils';
import { AddBankDialog } from './add-bank-dialog';
import { AddCurrencyDialog } from './add-currency-dialog';
import { formatCurrency } from '@/lib/currency-formatter';
import { Switch } from '@/components/ui/switch';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Checkbox } from '@/components/ui/checkbox';

type CheckItem = {
  id: string;
  checkNumber: string;
  bankId: string;
  bankName: string;
  checkDate: string;
  currency: string;
  amount: number;
};

type AllocationItem = {
  purchaseOrderId: string;
  amount: number;
};

const checkFormSchema = z.object({
  checkNumber: z.string().min(1, 'Check number is required'),
  bankId: z.string().min(1, 'Bank is required'),
  checkDate: z.string().min(1, 'Check date is required'),
  currency: z.string().min(1, 'Currency is required'),
  amount: z.coerce.number().min(0.01, 'Amount must be greater than 0'),
});

type Party = {
  id: string;
  name: string;
  type: 'customer' | 'supplier';
  originalId: string;
  balance: number;
};

const allocationSchema = z.object({
  purchaseOrderId: z.string().min(1, 'Invoice is required'),
  amount: z.coerce.number().min(0.01, 'Amount must be greater than 0'),
});

const paymentVoucherSchema = z.object({
  supplierId: z.string().min(1, 'Please select a supplier.'),
  amount: z.coerce.number().min(0.01, 'Amount must be greater than 0.'),
  paymentMethod: z.string().min(1, 'Please select a payment method.'),
  reference: z.string().optional(),
  notes: z.string().optional(),
  currencyCode: z.string().min(1, 'Currency is required'),
  exchangeRate: z.coerce.number().positive().optional(),
  rateDate: z.string().optional(),
  isAdvance: z.boolean().optional(),
  checkSource: z.enum(['issued', 'incoming']).optional().default('issued'),
  incomingCheckIds: z.array(z.string()).optional().default([]),
  postingStatus: z.enum(['draft', 'saved', 'posted']).optional().default('posted'),
  allocationMode: z.enum(['manual', 'oldest_first', 'newest_first', 'currency_oldest_first', 'currency_newest_first']).optional().default('manual'),
  allocations: z.array(allocationSchema).optional().default([]),
  checks: z.array(z.object({
    id: z.string(),
    checkNumber: z.string(),
    bankId: z.string(),
    bankName: z.string(),
    checkDate: z.string(),
    currency: z.string(),
    amount: z.coerce.number().min(0.01).optional(),
  })).optional().default([]),
});

const paymentFullEditSchema = z.object({
  amount: z.coerce.number().positive(),
  currencyCode: z.string().min(1),
  exchangeRate: z.coerce.number().positive(),
  isAdvance: z.boolean().optional(),
  postingStatus: z.enum(['draft', 'saved', 'posted']).optional().default('posted'),
  reference: z.string().optional(),
  notes: z.string().optional(),
  rateDate: z.string().optional(),
});

type SupplierPaymentVoucherFormProps = {
  suppliers: Supplier[];
  customers: Customer[];
  purchaseOrders: PurchaseOrder[];
  supplierPayments: SupplierPayment[];
  incomingChecks: IncomingCheck[];
  banks: Bank[];
  currencies: Currency[];
  defaultCurrency: Currency | null;
  initialEditPaymentId?: string;
  t: any;
  tGlobal: any;
  currencySymbol?: string;
};

export function SupplierPaymentVoucherForm({ suppliers, customers, purchaseOrders, supplierPayments, incomingChecks, banks, currencies, defaultCurrency, initialEditPaymentId, t, tGlobal, currencySymbol = '$' }: SupplierPaymentVoucherFormProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();
  const [isRefreshingParties, startRefreshParties] = useTransition();
  const { toast } = useToast();
  const [selectedPartyId, setSelectedPartyId] = useState<string>('');
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [bankOptions, setBankOptions] = useState<Bank[]>(banks);
  const [currencyOptions, setCurrencyOptions] = useState<Currency[]>(currencies);
  const [checks, setChecks] = useState<CheckItem[]>([]);
  const [selectedIncomingCheckIds, setSelectedIncomingCheckIds] = useState<string[]>([]);
  const [showCheckForm, setShowCheckForm] = useState(false);
  const [isAddBankDialogOpen, setIsAddBankDialogOpen] = useState(false);
  const [allocations, setAllocations] = useState<AllocationItem[]>([]);
  const [selectedInvoiceIds, setSelectedInvoiceIds] = useState<string[]>([]);
  const [lockedSupplierId, setLockedSupplierId] = useState<string>('');
  const [supplierLockById, setSupplierLockById] = useState<Record<string, string | null>>({});
  const [activeTab, setActiveTab] = useState<'create' | 'list'>('create');
  const [expandedPaymentId, setExpandedPaymentId] = useState<string | null>(null);
  const [previewPayment, setPreviewPayment] = useState<SupplierPayment | null>(null);
  const [editingPayment, setEditingPayment] = useState<SupplierPayment | null>(null);
  const [editAllocations, setEditAllocations] = useState<AllocationItem[]>([]);
  const [editingInCreatePaymentId, setEditingInCreatePaymentId] = useState<string | null>(initialEditPaymentId || null);
  const [paymentRows, setPaymentRows] = useState<SupplierPayment[]>(() =>
    [...supplierPayments].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
  );

  const baseCurrencyCode = defaultCurrency?.code || 'JOD';
  const exchangeRateLabel = `${t?.exchangeRateShort ?? 'سعر الصرف'} (${t?.against ?? 'مقابل'} ${baseCurrencyCode})`;

  const form = useForm<z.infer<typeof paymentVoucherSchema>>({
    resolver: zodResolver(paymentVoucherSchema),
    defaultValues: {
      supplierId: '',
      amount: 0,
      paymentMethod: 'cash',
      reference: '',
      notes: '',
        currencyCode: baseCurrencyCode,
        exchangeRate: 1,
        rateDate: format(new Date(), 'yyyy-MM-dd'),
        isAdvance: false,
      checkSource: 'issued',
      incomingCheckIds: [],
      postingStatus: 'posted',
      allocationMode: 'manual',
      checks: [],
    },
  });

  const checkForm = useForm<z.infer<typeof checkFormSchema>>({
    resolver: zodResolver(checkFormSchema),
    defaultValues: {
      checkNumber: '',
      bankId: '',
      checkDate: format(new Date(), 'yyyy-MM-dd'),
      currency: defaultCurrency?.code || 'JOD',
      amount: 0,
    },
  });

  const paymentEditForm = useForm<z.infer<typeof paymentFullEditSchema>>({
    resolver: zodResolver(paymentFullEditSchema),
    defaultValues: {
      amount: 0,
      currencyCode: baseCurrencyCode,
      exchangeRate: 1,
      isAdvance: false,
      postingStatus: 'posted',
      reference: '',
      notes: '',
      rateDate: format(new Date(), 'yyyy-MM-dd'),
    },
  });

  const parties = useMemo<Party[]>(() => {
    const supplierParties: Party[] = suppliers.map(s => ({
      id: `supplier:${s.id}`,
      name: s.name,
      type: 'supplier' as const,
      originalId: s.id,
      balance: s.balance
    }));
    const customerParties: Party[] = customers.map(c => ({
      id: `customer:${c.id}`,
      name: c.name,
      type: 'customer' as const,
      originalId: c.id,
      balance: c.balance
    }));
    return [...supplierParties, ...customerParties];
  }, [suppliers, customers]);

  const filteredParties = useMemo(() => {
    if (!searchTerm) return parties;
    return parties.filter(p => p.name.toLowerCase().includes(searchTerm.toLowerCase()));
  }, [parties, searchTerm]);

  const selectedParty = useMemo(() => {
    return parties.find(p => p.id === selectedPartyId);
  }, [selectedPartyId, parties]);

  const editingInCreatePayment = useMemo(() => {
    if (!editingInCreatePaymentId) return null;
    return paymentRows.find((entry) => entry.id === editingInCreatePaymentId) || null;
  }, [editingInCreatePaymentId, paymentRows]);
  const { lockStatus: createEditLockStatus } = useDocumentLock('supplier-payment', editingInCreatePaymentId || '', { enabled: !!editingInCreatePaymentId });
  const isCreateEditLocked = !!editingInCreatePaymentId && createEditLockStatus.isLocked;
  const { lockStatus: modalEditLockStatus } = useDocumentLock('supplier-payment', editingPayment?.id || '', { enabled: !!editingPayment?.id });
  const isModalEditLocked = !!editingPayment && modalEditLockStatus.isLocked;

  const watchedSupplierId = useWatch({ control: form.control, name: 'supplierId' });
  const selectedSupplierOrders = useMemo(() => {
    if (!watchedSupplierId) return [] as PurchaseOrder[];
    return purchaseOrders.filter((po) =>
      po.supplierId === watchedSupplierId
      && po.status !== 'cancelled'
      && (po.postingStatus || 'posted') === 'posted'
      && (po.amountDue || 0) > 0
    );
  }, [purchaseOrders, watchedSupplierId]);

  useEffect(() => {
    setAllocations([]);
    setSelectedInvoiceIds([]);
  }, [watchedSupplierId]);

  useEffect(() => {
    const validOrderIds = new Set(selectedSupplierOrders.map((order) => order.id));
    setAllocations((prev) => prev.filter((entry) => validOrderIds.has(entry.purchaseOrderId)));
    setSelectedInvoiceIds((prev) => prev.filter((id) => validOrderIds.has(id)));
  }, [selectedSupplierOrders]);

  useEffect(() => {
    const nextSelected = allocations
      .filter((entry) => Number(entry.amount || 0) > 0)
      .map((entry) => entry.purchaseOrderId);
    setSelectedInvoiceIds(nextSelected);
  }, [allocations]);

  useEffect(() => {
    return () => {
      if (lockedSupplierId) {
        void handleReleaseSupplierPaymentLock(lockedSupplierId);
      }
    };
  }, [lockedSupplierId]);

  useEffect(() => {
    const queryEditId = searchParams.get('editId') || initialEditPaymentId || '';
    if (!queryEditId) return;
    if (editingInCreatePaymentId === queryEditId) return;

    const paymentToEdit = paymentRows.find((entry) => entry.id === queryEditId);
    if (!paymentToEdit) return;

    setEditingInCreatePaymentId(paymentToEdit.id);
    setActiveTab('create');
    setSelectedPartyId(`supplier:${paymentToEdit.supplierId}`);
    form.reset({
      supplierId: paymentToEdit.supplierId,
      amount: Number(paymentToEdit.amount || 0),
      paymentMethod: (paymentToEdit.paymentMethod as any) || 'cash',
      reference: paymentToEdit.reference || '',
      notes: paymentToEdit.notes || '',
      currencyCode: paymentToEdit.currencyCode || baseCurrencyCode,
      exchangeRate: Number(paymentToEdit.exchangeRate || 1),
      rateDate: paymentToEdit.rateDate ? format(new Date(paymentToEdit.rateDate), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd'),
      isAdvance: paymentToEdit.isAdvance === true,
      checkSource: (paymentToEdit.paymentMethod === 'check' ? (paymentToEdit.checkSource || 'issued') : 'issued') as any,
      incomingCheckIds: Array.isArray(paymentToEdit.incomingCheckIds) ? paymentToEdit.incomingCheckIds : [],
      postingStatus: (paymentToEdit.postingStatus || 'posted') as any,
      allocationMode: 'manual',
      checks: [],
    });

    const nextAllocations = (Array.isArray(paymentToEdit.allocations) ? paymentToEdit.allocations : []).map((entry) => ({
      purchaseOrderId: entry.purchaseOrderId,
      amount: Number(entry.amount || 0),
    }));
    setAllocations(nextAllocations);
    setSelectedIncomingCheckIds(Array.isArray(paymentToEdit.incomingCheckIds) ? paymentToEdit.incomingCheckIds : []);
    setSelectedInvoiceIds(nextAllocations.filter((entry) => Number(entry.amount || 0) > 0).map((entry) => entry.purchaseOrderId));
  }, [searchParams, initialEditPaymentId, paymentRows, form, baseCurrencyCode, editingInCreatePaymentId]);

  const handleStartEditInCreate = (payment: SupplierPayment) => {
    setEditingInCreatePaymentId(payment.id);
    setActiveTab('create');
    setSelectedPartyId(`supplier:${payment.supplierId}`);
    form.reset({
      supplierId: payment.supplierId,
      amount: Number(payment.amount || 0),
      paymentMethod: (payment.paymentMethod as any) || 'cash',
      reference: payment.reference || '',
      notes: payment.notes || '',
      currencyCode: payment.currencyCode || baseCurrencyCode,
      exchangeRate: Number(payment.exchangeRate || 1),
      rateDate: payment.rateDate ? format(new Date(payment.rateDate), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd'),
      isAdvance: payment.isAdvance === true,
      checkSource: (payment.paymentMethod === 'check' ? (payment.checkSource || 'issued') : 'issued') as any,
      incomingCheckIds: Array.isArray(payment.incomingCheckIds) ? payment.incomingCheckIds : [],
      postingStatus: (payment.postingStatus || 'posted') as any,
      allocationMode: 'manual',
      checks: [],
    });

    const nextAllocations = (Array.isArray(payment.allocations) ? payment.allocations : []).map((entry) => ({
      purchaseOrderId: entry.purchaseOrderId,
      amount: Number(entry.amount || 0),
    }));
    setAllocations(nextAllocations);
    setSelectedIncomingCheckIds(Array.isArray(payment.incomingCheckIds) ? payment.incomingCheckIds : []);
    setSelectedInvoiceIds(nextAllocations.filter((entry) => Number(entry.amount || 0) > 0).map((entry) => entry.purchaseOrderId));
    router.replace(`/admin/purchases/payment?editId=${payment.id}`);
  };

  useEffect(() => {
    if (!popoverOpen) return;
    const supplierIds = filteredParties
      .filter((party) => party.type === 'supplier')
      .map((party) => party.originalId);
    if (supplierIds.length === 0) {
      setSupplierLockById({});
      return;
    }

    let active = true;
    (async () => {
      const result = await handleGetSupplierPaymentLocksStatus(supplierIds);
      if (!active || !result?.success || !result.statuses) return;
      const next: Record<string, string | null> = {};
      supplierIds.forEach((id) => {
        const status = result.statuses[id];
        next[id] = status?.locked ? (status.lockedBy || 'مستخدم آخر') : null;
      });
      setSupplierLockById(next);
    })();

    return () => {
      active = false;
    };
  }, [popoverOpen, filteredParties]);

  const watchedAmount = useWatch({ control: form.control, name: 'amount' });
  const watchedCurrency = useWatch({ control: form.control, name: 'currencyCode' });
  const watchedExchangeRate = useWatch({ control: form.control, name: 'exchangeRate' });
  const watchedIsAdvance = useWatch({ control: form.control, name: 'isAdvance' });
  const watchedAllocationMode = useWatch({ control: form.control, name: 'allocationMode' });
  const watchedCheckSource = useWatch({ control: form.control, name: 'checkSource' });

  const availableIncomingChecks = useMemo(() => {
    return incomingChecks.filter((entry) => entry.status === 'pending' && (!entry.endorsementStatus || entry.endorsementStatus === 'none'));
  }, [incomingChecks]);

  const selectedIncomingChecksTotalInPaymentCurrency = useMemo(() => {
    const paymentCurrency = watchedCurrency || baseCurrencyCode;
    return availableIncomingChecks
      .filter((entry) => selectedIncomingCheckIds.includes(entry.id))
      .reduce((sum, entry) => {
        const checkCurrency = entry.currency || baseCurrencyCode;
        return sum + convertAmountBetweenCurrencies(Number(entry.amount || 0), checkCurrency, paymentCurrency);
      }, 0);
  }, [availableIncomingChecks, selectedIncomingCheckIds, watchedCurrency, baseCurrencyCode]);

  const incomingChecksSelectionDelta = Number((Number(watchedAmount || 0) - selectedIncomingChecksTotalInPaymentCurrency).toFixed(2));

  // F2 keyboard shortcut handler
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'F2' && activeTab === 'create') {
        e.preventDefault();
        handleCreateSubmitWithStatus('saved');
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [activeTab]);

  const getRateToBase = (code?: string) => {
    const normalized = (code || baseCurrencyCode).trim() || baseCurrencyCode;
    if (normalized === baseCurrencyCode) return 1;
    const found = currencyOptions.find((entry) => entry.code === normalized);
    const rate = Number(found?.exchangeRate || 0);
    return Number.isFinite(rate) && rate > 0 ? rate : 1;
  };

  const convertAmountBetweenCurrencies = (amount: number, fromCode?: string, toCode?: string) => {
    const numeric = Number(amount || 0);
    if (!Number.isFinite(numeric) || numeric <= 0) return 0;
    const from = (fromCode || baseCurrencyCode).trim() || baseCurrencyCode;
    const to = (toCode || baseCurrencyCode).trim() || baseCurrencyCode;
    if (from === to) return numeric;
    const fromRate = getRateToBase(from);
    const toRate = getRateToBase(to);
    // Convert: amount in fromCurrency -> base currency (divide by fromRate) -> toCurrency (multiply by toRate)
    return Number(((numeric / fromRate) * toRate).toFixed(4));
  };

  const getCapturedInvoiceRate = (order: PurchaseOrder) => {
    const invoiceCurrency = order.currencyCode || baseCurrencyCode;
    const capturedRate = Number(order.exchangeRate || 0);
    const dueRate = Number(order.amountDue || 0) > 0 ? Number(order.amountDueBase || 0) / Number(order.amountDue || 1) : 0;
    const grandRate = Number(order.grandTotal || 0) > 0 ? Number(order.grandTotalBase || 0) / Number(order.grandTotal || 1) : 0;
    if (Number.isFinite(capturedRate) && capturedRate > 0) return capturedRate;
    if (Number.isFinite(dueRate) && dueRate > 0) return dueRate;
    if (Number.isFinite(grandRate) && grandRate > 0) return grandRate;
    return getRateToBase(invoiceCurrency);
  };

  useEffect(() => {
    if (!watchedAllocationMode || watchedAllocationMode === 'manual') return;
    if (watchedIsAdvance) {
      setAllocations([]);
      return;
    }
    const auto = buildAutoAllocations(
      selectedSupplierOrders,
      Number(watchedAmount || 0),
      watchedAllocationMode as 'oldest_first' | 'newest_first' | 'currency_oldest_first' | 'currency_newest_first',
      watchedCurrency || baseCurrencyCode,
      baseCurrencyCode,
    );
    setAllocations(auto.rows);
  }, [watchedAllocationMode, watchedIsAdvance, watchedAmount, watchedCurrency, selectedSupplierOrders, baseCurrencyCode]);

  const totalAllocated = useMemo(() => allocations.reduce((sum, a) => sum + (a.amount || 0), 0), [allocations]);
  const paymentExchangeRateEffective = useMemo(() => {
    const paymentCurrency = watchedCurrency || baseCurrencyCode;
    if (paymentCurrency === baseCurrencyCode) return 1;
    const enteredRate = Number(watchedExchangeRate || 0);
    if (Number.isFinite(enteredRate) && enteredRate > 0) return enteredRate;
    return getRateToBase(paymentCurrency);
  }, [watchedCurrency, watchedExchangeRate, baseCurrencyCode]);

  const liveTotalFxDifferenceBase = useMemo(() => {
    return allocations.reduce((sum, entry) => {
      const order = selectedSupplierOrders.find((row) => row.id === entry.purchaseOrderId);
      if (!order) return sum;
      const allocAmount = Number(entry.amount || 0);
      if (!Number.isFinite(allocAmount) || allocAmount <= 0) return sum;
      const invoiceCurrency = order.currencyCode || baseCurrencyCode;
      const invoiceRate = Number(getCapturedInvoiceRate(order));
      const allocatedInPaymentCurrency = convertAmountBetweenCurrencies(allocAmount, invoiceCurrency, watchedCurrency || baseCurrencyCode);
      // baseAtInvoiceRate: convert invoice currency to base (ILS) using captured rate
      const baseAtInvoiceRate = invoiceCurrency === baseCurrencyCode 
        ? allocAmount 
        : allocAmount / (Number.isFinite(invoiceRate) && invoiceRate > 0 ? invoiceRate : 1);
      const baseAtPaymentRate = (watchedCurrency || baseCurrencyCode) === baseCurrencyCode
        ? allocatedInPaymentCurrency
        : allocatedInPaymentCurrency / (Number.isFinite(paymentExchangeRateEffective) && paymentExchangeRateEffective > 0 ? paymentExchangeRateEffective : 1);
      return sum + (baseAtPaymentRate - baseAtInvoiceRate);
    }, 0);
  }, [allocations, selectedSupplierOrders, watchedCurrency, baseCurrencyCode, paymentExchangeRateEffective]);

  const totalAllocatedInPaymentCurrency = useMemo(() => {
    return allocations.reduce((sum, entry) => {
      const order = selectedSupplierOrders.find((row) => row.id === entry.purchaseOrderId);
      const invoiceCurrency = order?.currencyCode || baseCurrencyCode;
      return sum + convertAmountBetweenCurrencies(Number(entry.amount || 0), invoiceCurrency, watchedCurrency || baseCurrencyCode);
    }, 0);
  }, [allocations, selectedSupplierOrders, watchedCurrency, baseCurrencyCode]);
  const allocationDelta = useMemo(() => Number((Number(watchedAmount || 0) - totalAllocatedInPaymentCurrency).toFixed(2)), [watchedAmount, totalAllocatedInPaymentCurrency]);

  const buildAutoAllocations = (
    orders: PurchaseOrder[],
    amount: number,
    mode: 'oldest_first' | 'newest_first' | 'currency_oldest_first' | 'currency_newest_first',
    paymentCurrency: string,
    baseCode: string,
  ) => {
    const withCurrencyFilter = mode === 'currency_oldest_first' || mode === 'currency_newest_first';
    const sorted = [...orders]
      .filter((order) => order.status !== 'cancelled')
      .filter((order) => Number(order.amountDue || 0) > 0)
      .filter((order) => !withCurrencyFilter || (order.currencyCode || baseCode) === paymentCurrency)
      .sort((a, b) => {
        const aTime = new Date(a.date || 0).getTime();
        const bTime = new Date(b.date || 0).getTime();
        return (mode === 'oldest_first' || mode === 'currency_oldest_first') ? (aTime - bTime) : (bTime - aTime);
      });

    let remainingPaymentCurrency = Number(amount || 0);
    const rows: AllocationItem[] = [];
    sorted.forEach((order) => {
      if (remainingPaymentCurrency <= 0) return;
      const invoiceCurrency = order.currencyCode || baseCode;
      const dueInvoiceCurrency = Number(order.amountDue || 0);
      if (!Number.isFinite(dueInvoiceCurrency) || dueInvoiceCurrency <= 0) return;

      const duePaymentCurrency = convertAmountBetweenCurrencies(dueInvoiceCurrency, invoiceCurrency, paymentCurrency);
      const paidInPaymentCurrency = Math.min(remainingPaymentCurrency, duePaymentCurrency);
      if (paidInPaymentCurrency > 0) {
        const paidInInvoiceCurrency = convertAmountBetweenCurrencies(paidInPaymentCurrency, paymentCurrency, invoiceCurrency);
        rows.push({ purchaseOrderId: order.id, amount: Number(Math.min(dueInvoiceCurrency, paidInInvoiceCurrency).toFixed(2)) });
        remainingPaymentCurrency = Number((remainingPaymentCurrency - paidInPaymentCurrency).toFixed(2));
      }
    });

    return { rows, remaining: remainingPaymentCurrency };
  };

  const calculateTotalInPaymentCurrency = (rows: AllocationItem[]) => {
    return rows.reduce((sum, entry) => {
      const order = selectedSupplierOrders.find((row) => row.id === entry.purchaseOrderId);
      const invoiceCurrency = order?.currencyCode || baseCurrencyCode;
      return sum + convertAmountBetweenCurrencies(Number(entry.amount || 0), invoiceCurrency, watchedCurrency || baseCurrencyCode);
    }, 0);
  };

  const syncAmountWithAllocations = (rows: AllocationItem[]) => {
    const total = calculateTotalInPaymentCurrency(rows);
    form.setValue('amount', Number(total.toFixed(2)), { shouldDirty: true, shouldValidate: true });
  };

  const buildRowsFromOrders = (orders: PurchaseOrder[]) => {
    return orders
      .filter((order) => Number(order.amountDue || 0) > 0)
      .map((order) => ({ purchaseOrderId: order.id, amount: Number(Number(order.amountDue || 0).toFixed(2)) }));
  };

  const handleSelectAllInvoices = () => {
    form.setValue('allocationMode', 'manual', { shouldDirty: true, shouldValidate: true });
    const rows = buildRowsFromOrders(selectedSupplierOrders);
    setAllocations(rows);
    syncAmountWithAllocations(rows);
  };

  const handleSelectCurrencyInvoices = () => {
    form.setValue('allocationMode', 'manual', { shouldDirty: true, shouldValidate: true });
    const currentCurrency = watchedCurrency || baseCurrencyCode;
    const rows = buildRowsFromOrders(selectedSupplierOrders.filter((order) => (order.currencyCode || baseCurrencyCode) === currentCurrency));
    setAllocations(rows);
    syncAmountWithAllocations(rows);
  };

  const handleClearSelectedInvoices = () => {
    form.setValue('allocationMode', 'manual', { shouldDirty: true, shouldValidate: true });
    setAllocations([]);
    form.setValue('amount', 0, { shouldDirty: true, shouldValidate: true });
  };

  const onSubmit = (data: z.infer<typeof paymentVoucherSchema>) => {
    if (isCreateEditLocked) {
      return;
    }

    // Validate check fields when payment method is check
    if (data.paymentMethod === 'check') {
      if (data.checkSource === 'incoming') {
        if (!selectedIncomingCheckIds || selectedIncomingCheckIds.length === 0) {
          toast({
            title: tGlobal?.error,
            description: t?.selectIncomingChecks ?? 'الرجاء اختيار شيك وارد واحد على الأقل',
            variant: 'destructive',
          });
          return;
        }
      } else if (!checks || checks.length === 0) {
        toast({
          title: tGlobal?.error,
          description: t?.addAtLeastOneCheck ?? 'يجب إضافة شيك واحد على الأقل',
          variant: 'destructive',
        });
        return;
      }
    }

    let allocationPayload = allocations.filter((a) => a.amount > 0.0001);
    if (allocationPayload.length === 0 && watchedAllocationMode && watchedAllocationMode !== 'manual') {
      const auto = buildAutoAllocations(
        selectedSupplierOrders,
        Number(data.amount || 0),
        watchedAllocationMode as any,
        watchedCurrency || baseCurrencyCode,
        baseCurrencyCode,
      );
      allocationPayload = auto.rows;
      if (auto.rows.length > 0) setAllocations(auto.rows);
    }
    const actualPaymentCurrency = data.currencyCode || baseCurrencyCode;
    if (actualPaymentCurrency !== baseCurrencyCode && !data.isAdvance) {
      if (allocationPayload.length === 0) {
        toast({
          title: tGlobal?.error,
          description: t?.allocationRequired ?? 'يجب ربط الدفعة بفواتير عند الدفع بعملة أجنبية',
          variant: 'destructive',
        });
        return;
      }
      // Allow partial allocations - amount doesn't need to match exactly
      // Real validation happens at database level
    }

    for (const alloc of allocationPayload) {
      const order = selectedSupplierOrders.find((o) => o.id === alloc.purchaseOrderId);
      if (order && alloc.amount - (order.amountDue || 0) > 0.01) {
        toast({
          title: tGlobal?.error,
          description: t?.allocationExceeds ?? 'قيمة التوزيع تتجاوز الرصيد المتبقي للفاتورة',
          variant: 'destructive',
        });
        return;
      }
    }

    startTransition(async () => {
      try {
        if (editingInCreatePaymentId) {
          const updateResult = await handleUpdateSupplierPaymentFull({
            paymentId: editingInCreatePaymentId,
            amount: Number(data.amount || 0),
            currencyCode: data.currencyCode || baseCurrencyCode,
            exchangeRate: Number(data.exchangeRate || 1),
            isAdvance: data.isAdvance === true,
            postingStatus: data.postingStatus || 'posted',
            reference: data.reference,
            notes: data.notes,
            rateDate: data.rateDate,
            allocations: allocationPayload,
          });

          if (updateResult?.success) {
            if (updateResult.payment) {
              setPaymentRows((prev) => prev.map((row) => (row.id === editingInCreatePaymentId ? (updateResult.payment as SupplierPayment) : row)));
            }
            setEditingInCreatePaymentId(null);
            setActiveTab('list');
            toast({ title: t?.updateSuccessTitle ?? 'تم تحديث السند بنجاح' });
            router.replace('/admin/purchases/payment');
          } else {
            toast({
              title: tGlobal?.error,
              description: (updateResult?.error || t?.paymentError || 'تعذر تحديث السند'),
              variant: 'destructive',
            });
          }
          return;
        }

        const result = await handleSupplierPayment({
          ...data,
          checkSource: data.checkSource || 'issued',
          incomingCheckIds: data.checkSource === 'incoming' ? selectedIncomingCheckIds : [],
          postingStatus: data.postingStatus || 'posted',
          checks,
          allocations: allocationPayload,
        });
        if (result?.success) {
          if (lockedSupplierId) {
            await handleReleaseSupplierPaymentLock(lockedSupplierId);
            setLockedSupplierId('');
          }
          if (result?.payment) {
            setPaymentRows((prev) => [result.payment as SupplierPayment, ...prev.filter((row) => row.id !== (result.payment as SupplierPayment).id)]);
          }
          setActiveTab('list');
          toast({
            title: t?.paymentRecorded ?? 'تم تسجيل الدفع',
            description: `${t?.amount}: ${currencySymbol}${data.amount.toFixed(2)}`,
          });
          form.reset({
            supplierId: '',
            amount: 0,
            paymentMethod: 'cash',
            reference: '',
            notes: '',
            currencyCode: baseCurrencyCode,
            exchangeRate: 1,
            rateDate: format(new Date(), 'yyyy-MM-dd'),
            isAdvance: false,
            checkSource: 'issued',
            incomingCheckIds: [],
            postingStatus: 'posted',
            allocationMode: 'manual',
            checks: [],
          });
          checkForm.reset();
          setChecks([]);
          setSelectedIncomingCheckIds([]);
          setAllocations([]);
          setSelectedInvoiceIds([]);
        } else {
          const errorText = String(result?.error || '');
          if (errorText.startsWith('SUPPLIER_PAYMENT_LOCKED:')) {
            const lockedBy = errorText.split(':')[1] || (t?.anotherUser ?? 'مستخدم آخر');
            toast({
              title: tGlobal?.error,
              description: `${t?.beneficiaryLockedBy ?? 'هذا المستفيد قيد الإدخال حالياً بواسطة'} ${lockedBy}`,
              variant: 'destructive',
            });
            return;
          }
          toast({
            title: tGlobal?.error,
            description: ((result?.error ?? t?.paymentError) || 'حدث خطأ في تسجيل الدفع'),
            variant: 'destructive',
          });
        }
      } catch (error) {
        toast({
          title: tGlobal?.error,
          description: t?.paymentError ?? 'حدث خطأ في تسجيل الدفع',
          variant: 'destructive',
        });
      }
    });
  };

  const handleAddCheck = (formValues: z.infer<typeof checkFormSchema>) => {
    const bank = bankOptions.find((b) => b.id === formValues.bankId);
    const newCheck: CheckItem = {
      id: Math.random().toString(36).substr(2, 9),
      checkNumber: formValues.checkNumber,
      bankId: formValues.bankId,
      bankName: bank?.name || '',
      checkDate: formValues.checkDate,
      currency: formValues.currency,
      amount: Number(formValues.amount || 0),
    };
    setChecks([...checks, newCheck]);
    checkForm.reset({
      checkNumber: '',
      bankId: '',
      checkDate: format(new Date(), 'yyyy-MM-dd'),
      currency: defaultCurrency?.code || 'JOD',
      amount: 0,
    });
    setShowCheckForm(false);
    toast({
      title: t?.checkAddedTitle ?? 'تم إضافة الشيك',
      description: `${t?.checkNumber ?? 'رقم الشيك'}: ${formValues.checkNumber}`,
    });
  };

  const handleRemoveCheck = (id: string) => {
    setChecks(checks.filter((check) => check.id !== id));
  };

  const handleAllocationChange = (purchaseOrderId: string, value: number) => {
    const next = (() => {
      const filtered = allocations.filter((a) => a.purchaseOrderId !== purchaseOrderId);
      if (!Number.isFinite(value) || value <= 0) return filtered;
      return [...filtered, { purchaseOrderId, amount: value }];
    })();
    setAllocations(next);
    syncAmountWithAllocations(next);
  };

  const handleInvoiceSelectionChange = (order: PurchaseOrder, checked: boolean) => {
    form.setValue('allocationMode', 'manual', { shouldDirty: true, shouldValidate: true });
    const due = Number(order.amountDue || 0);
    const next = checked
      ? [
          ...allocations.filter((entry) => entry.purchaseOrderId !== order.id),
          { purchaseOrderId: order.id, amount: Number(due.toFixed(2)) },
        ]
      : allocations.filter((entry) => entry.purchaseOrderId !== order.id);

    setAllocations(next);
    setSelectedInvoiceIds((prev) => {
      if (checked) return Array.from(new Set([...prev, order.id]));
      return prev.filter((id) => id !== order.id);
    });
    syncAmountWithAllocations(next);
  };

  const handleCurrencyChange = (code: string) => {
    const currentCode = form.getValues('currencyCode');
    if (String(currentCode || '') !== String(code || '')) {
      // Currency switch starts a fresh allocation flow to avoid mixed-rate residuals.
      setAllocations([]);
      setSelectedInvoiceIds([]);
      setSelectedIncomingCheckIds([]);
      setChecks([]);
      form.setValue('amount', 0, { shouldDirty: true, shouldValidate: true });
      form.setValue('incomingCheckIds', [], { shouldDirty: true, shouldValidate: true });
      form.setValue('allocationMode', 'manual', { shouldDirty: true, shouldValidate: true });
    }
    const matched = currencyOptions.find((c) => c.code === code);
    form.setValue('currencyCode', code, { shouldDirty: true, shouldValidate: true });
    form.setValue('exchangeRate', matched?.exchangeRate || 1, { shouldDirty: true, shouldValidate: true });
    form.setValue('isAdvance', false, { shouldDirty: true, shouldValidate: true });
  };

  const getSupplierNameById = (supplierId: string) => {
    const supplier = suppliers.find((entry) => entry.id === supplierId);
    return supplier?.name || supplierId;
  };

  const editCurrencyCode = useWatch({ control: paymentEditForm.control, name: 'currencyCode' });
  const editIsAdvance = useWatch({ control: paymentEditForm.control, name: 'isAdvance' });

  const editableOrders = useMemo(() => {
    if (!editingPayment) return [] as PurchaseOrder[];
    return purchaseOrders.filter((po) => po.supplierId === editingPayment.supplierId && po.status !== 'cancelled');
  }, [editingPayment, purchaseOrders]);

  const handleOpenEdit = (payment: SupplierPayment) => {
    setEditingPayment(payment);
    paymentEditForm.reset({
      amount: Number(payment.amount || 0),
      currencyCode: payment.currencyCode || baseCurrencyCode,
      exchangeRate: Number(payment.exchangeRate || 1),
      isAdvance: payment.isAdvance === true,
      postingStatus: (payment.postingStatus || 'posted') as any,
      reference: payment.reference || '',
      notes: payment.notes || '',
      rateDate: payment.rateDate ? format(new Date(payment.rateDate), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd'),
    });

    setEditAllocations(
      (Array.isArray(payment.allocations) ? payment.allocations : []).map((entry) => ({
        purchaseOrderId: entry.purchaseOrderId,
        amount: Number(entry.amount || 0),
      }))
    );
  };

  const handleEditAllocationChange = (purchaseOrderId: string, amount: number) => {
    setEditAllocations((prev) => {
      const filtered = prev.filter((entry) => entry.purchaseOrderId !== purchaseOrderId);
      if (!Number.isFinite(amount) || amount <= 0) return filtered;
      return [...filtered, { purchaseOrderId, amount }];
    });
  };

  const handleCancelPayment = (payment: SupplierPayment) => {
    if (payment.status === 'cancelled') return;
    const confirmed = typeof window !== 'undefined'
      ? window.confirm(t?.cancelConfirmMessage ?? 'هل أنت متأكد من إلغاء هذا السند؟ سيتم عكس الأثر المحاسبي والتوزيعات.')
      : true;
    if (!confirmed) return;

    startTransition(async () => {
      const result = await handleCancelSupplierPayment({ paymentId: payment.id });
      if (result?.success && result.payment) {
        setPaymentRows((prev) => prev.map((row) => (row.id === payment.id ? (result.payment as SupplierPayment) : row)));
        setExpandedPaymentId((prev) => (prev === payment.id ? null : prev));
        toast({ title: t?.cancelSuccessTitle ?? 'تم إلغاء السند بنجاح' });
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: result?.error || (t?.cancelFailed ?? 'تعذر إلغاء السند'),
          variant: 'destructive',
        });
      }
    });
  };

  const handleUpdatePaymentFull = (values: z.infer<typeof paymentFullEditSchema>) => {
    if (!editingPayment || isModalEditLocked) return;

    startTransition(async () => {
      const result = await handleUpdateSupplierPaymentFull({
        paymentId: editingPayment.id,
        amount: Number(values.amount || 0),
        currencyCode: values.currencyCode || baseCurrencyCode,
        exchangeRate: Number(values.exchangeRate || 1),
        isAdvance: values.isAdvance === true,
        postingStatus: values.postingStatus || 'posted',
        reference: values.reference,
        notes: values.notes,
        rateDate: values.rateDate,
        allocations: editAllocations.filter((entry) => Number(entry.amount || 0) > 0.0001),
      });

      if (result?.success) {
        if (result.payment) {
          setPaymentRows((prev) => prev.map((row) => (row.id === editingPayment.id ? (result.payment as SupplierPayment) : row)));
        }
        setEditingPayment(null);
        toast({ title: t?.updateSuccessTitle ?? 'تم تحديث السند بنجاح' });
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: result?.error || (t?.paymentError ?? 'تعذر تحديث السند'),
          variant: 'destructive',
        });
      }
    });
  };

  const handleCreateSubmitWithStatus = (status: 'draft' | 'saved' | 'posted') => {
    form.setValue('postingStatus', status, { shouldDirty: true, shouldValidate: true });
    void form.handleSubmit(onSubmit)();
  };

  return (
    <div className="space-y-6 w-full">
    <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'create' | 'list')} className="w-full">
      <TabsList className="w-full justify-start overflow-x-auto rounded-lg border bg-muted/40 p-1">
        <TabsTrigger value="create">{t?.createPaymentVoucherTab ?? 'إنشاء سند صرف'}</TabsTrigger>
        <TabsTrigger value="list">{t?.paymentVouchersListTab ?? 'عرض سندات الصرف'}</TabsTrigger>
      </TabsList>

    <TabsContent value="create" className="mt-4">
    <Card className="border shadow-sm">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)}>
          <CardHeader>
            <CardTitle>
              {editingInCreatePayment
                ? `${t?.edit ?? 'تعديل'} - ${editingInCreatePayment.id}`
                : (t?.paymentVoucher ?? 'سند الدفع')}
            </CardTitle>
            <CardDescription>
              {editingInCreatePayment
                ? (t?.editPaymentVoucherDescription ?? 'أنت الآن في وضع تعديل السند داخل شاشة الإنشاء مع نفس التفاصيل والميزات.')
                : (t?.paymentVoucherDescription ?? 'أدخل بيانات السند ثم وزع الدفعة على الفواتير مع متابعة فرق الصرف مباشرة.')}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="rounded-xl border p-4 sm:p-5 space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
                <FormItem>
                  <FormLabel>{t?.voucherNumber ?? 'رقم السند'}</FormLabel>
                  <Input
                    readOnly
                    disabled
                    placeholder="Auto-generated"
                    value={editingInCreatePayment?.id || `V/${format(new Date(), 'yyyy')}/AUTO`}
                  />
                </FormItem>

                <FormItem>
                  <FormLabel>{t?.date ?? 'التاريخ'}</FormLabel>
                  <Input
                    readOnly
                    disabled
                    value={editingInCreatePayment?.date ? format(new Date(editingInCreatePayment.date), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd')}
                  />
                </FormItem>

                <FormField
                  control={form.control}
                  name="supplierId"
                  render={({ field }) => (
                    <FormItem className="xl:col-span-2">
                      <FormLabel>{t?.selectParty ?? 'اختر مورداً أو زبوناً...'}</FormLabel>
                      <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              role="combobox"
                              className={cn("w-full justify-between", !selectedPartyId && "text-muted-foreground")}
                            >
                              {selectedParty
                                ? `${selectedParty.name} (${selectedParty.type === 'supplier' ? t?.supplierLabel ?? 'مورد' : t?.customerLabel ?? 'زبون'}) - ${formatCurrency(selectedParty.balance, currencySymbol)}`
                                : (t?.selectParty ?? 'اختر مورداً أو زبوناً...')}
                              <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-[--radix-popover-trigger-width] p-0">
                          <div className="p-2 space-y-2">
                            <div className="flex items-center gap-2">
                              <Input
                                placeholder={t?.searchParty ?? "ابحث عن مورد أو زبون..."}
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                autoFocus
                              />
                              <Button
                                type="button"
                                variant="outline"
                                size="icon"
                                title={t?.refreshPartyList ?? 'تحديث القائمة'}
                                disabled={isRefreshingParties}
                                onClick={() => {
                                  startRefreshParties(() => {
                                    router.refresh();
                                  });
                                }}
                              >
                                {isRefreshingParties
                                  ? <Loader2 className="h-4 w-4 animate-spin" />
                                  : <RefreshCw className="h-4 w-4" />}
                              </Button>
                            </div>
                          </div>
                          <div className="max-h-60 overflow-y-auto">
                            {filteredParties.map((party) => (
                              (() => {
                                const lockedBy = party.type === 'supplier' ? supplierLockById[party.originalId] : null;
                                const isLockedByOther = Boolean(lockedBy);
                                return (
                              <div
                                key={party.id}
                                onClick={async () => {
                                  if (party.type === 'supplier') {
                                    if (isLockedByOther) {
                                      toast({
                                        title: tGlobal?.error ?? 'خطأ',
                                        description: `${t?.beneficiaryLockedBy ?? 'هذا المستفيد قيد الإدخال حالياً بواسطة'} ${lockedBy}`,
                                        variant: 'destructive',
                                      });
                                      return;
                                    }

                                    if (lockedSupplierId && lockedSupplierId !== party.originalId) {
                                      await handleReleaseSupplierPaymentLock(lockedSupplierId);
                                      setLockedSupplierId('');
                                    }

                                    const lockResult = await handleAcquireSupplierPaymentLock(party.originalId);
                                    if (!lockResult?.success) {
                                      toast({
                                        title: tGlobal?.error ?? 'خطأ',
                                        description: `${t?.beneficiaryLockedBy ?? 'هذا المستفيد قيد الإدخال حالياً بواسطة'} ${lockResult?.lockedBy || (t?.anotherUser ?? 'مستخدم آخر')}`,
                                        variant: 'destructive',
                                      });
                                      return;
                                    }

                                    field.onChange(party.originalId);
                                    setLockedSupplierId(party.originalId);
                                  }
                                  setSelectedPartyId(party.id);
                                  setPopoverOpen(false);
                                  setSearchTerm('');
                                }}
                                className={cn(
                                  "relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent hover:bg-accent",
                                  isLockedByOther && "opacity-60",
                                )}
                                data-selected={party.id === selectedPartyId}
                              >
                                <Check
                                  className={cn(
                                    "me-2 h-4 w-4",
                                    party.id === selectedPartyId ? "opacity-100" : "opacity-0"
                                  )}
                                />
                                <span className="flex-1">{party.name}</span>
                                <span className="text-xs text-muted-foreground">
                                  ({party.type === 'supplier' ? t?.supplierLabel ?? 'مورد' : t?.customerLabel ?? 'زبون'}) - {formatCurrency(party.balance, currencySymbol)}
                                </span>
                                {party.type === 'supplier' && (
                                  <span className="ms-2 text-[11px] text-muted-foreground">
                                    {isLockedByOther ? `${t?.lockedBy ?? 'محجوز بواسطة'} ${lockedBy}` : (t?.available ?? 'متاح')}
                                  </span>
                                )}
                              </div>
                                );
                              })()
                            ))}
                          </div>
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="paymentMethod"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.paymentMethod ?? 'طريقة الدفع'}</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="cash">{t?.cash ?? 'نقداً'}</SelectItem>
                          <SelectItem value="check">{t?.check ?? 'شيك'}</SelectItem>
                          <SelectItem value="bank_transfer">{t?.bankTransfer ?? 'تحويل بنكي'}</SelectItem>
                          <SelectItem value="credit">{t?.credit ?? 'حساب دائن'}</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="amount"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.amount ?? 'المبلغ'}</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          min="0"
                          placeholder="0.00"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="reference"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.reference ?? 'المرجع'}</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="Check #, Transfer ID, etc."
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="currencyCode"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.currency ?? 'العملة'}</FormLabel>
                      <Select onValueChange={handleCurrencyChange} value={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {currencyOptions.map((currency) => (
                            <SelectItem key={currency.code} value={currency.code}>
                              {currency.code} - {currency.name} ({currency.symbol})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="exchangeRate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{exchangeRateLabel}</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.0001"
                          min="0"
                          placeholder="1.0000"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="rateDate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.rateDate ?? 'تاريخ السعر'}</FormLabel>
                      <FormControl>
                        <Input type="date" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="flex items-center justify-between rounded-lg border px-4 py-3 bg-muted/30">
                <div>
                  <p className="text-sm font-medium">{t?.advanceToggle ?? 'تسجيل كدفعة مقدمة'}</p>
                  <p className="text-xs text-muted-foreground">
                    {t?.advanceHelper ?? 'عند التفعيل، لن يُطلب ربط الدفعة بفواتير حالية.'}
                  </p>
                </div>
                <FormField
                  control={form.control}
                  name="isAdvance"
                  render={({ field }) => (
                    <Switch checked={field.value} onCheckedChange={field.onChange} />
                  )}
                />
              </div>
            </div>

            <div className="space-y-3 rounded-md border p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium">{t?.allocations ?? 'توزيع الدفعة على الفواتير'}</p>
                  <p className="text-xs text-muted-foreground">
                    {watchedCurrency !== baseCurrencyCode && !watchedIsAdvance
                      ? (t?.allocationHint ?? 'مطلوب ربط كامل للدفعة عند الدفع بعملة أجنبية.')
                      : (t?.allocationOptional ?? 'يمكن ربط الدفعة بالفواتير المفتوحة لهذا المورد.')}
                  </p>
                </div>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button type="button" variant="outline" size="sm" className="gap-2" disabled={watchedIsAdvance}>
                      {t?.allocations ?? 'توزيع الدفعة'}
                      <ChevronDown className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end" className="w-56">
                    <DropdownMenuItem 
                      onClick={() => form.setValue('allocationMode', 'manual', { shouldDirty: true, shouldValidate: true })}
                    >
                      {t?.allocationManual ?? 'توزيع يدوي'}
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem 
                      onClick={() => form.setValue('allocationMode', 'oldest_first', { shouldDirty: true, shouldValidate: true })}
                    >
                      {t?.allocationOldest ?? 'الأقدم أولاً'}
                    </DropdownMenuItem>
                    <DropdownMenuItem 
                      onClick={() => form.setValue('allocationMode', 'newest_first', { shouldDirty: true, shouldValidate: true })}
                    >
                      {t?.allocationNewest ?? 'الأحدث أولاً'}
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem 
                      onClick={() => form.setValue('allocationMode', 'currency_oldest_first', { shouldDirty: true, shouldValidate: true })}
                    >
                      {t?.allocationCurrencyOldest ?? 'نفس العملة - الأقدم أولاً'}
                    </DropdownMenuItem>
                    <DropdownMenuItem 
                      onClick={() => form.setValue('allocationMode', 'currency_newest_first', { shouldDirty: true, shouldValidate: true })}
                    >
                      {t?.allocationCurrencyNewest ?? 'نفس العملة - الأحدث أولاً'}
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={handleSelectAllInvoices}>
                      {t?.selectAllInvoices ?? 'تحديد كل الفواتير'}
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={handleSelectCurrencyInvoices}>
                      {t?.selectSameCurrencyInvoices ?? 'تحديد نفس العملة'}
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={handleClearSelectedInvoices}>
                      {t?.clearSelections ?? 'إلغاء التحديد'}
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
              
              <div className="text-xs">
                <span className="text-muted-foreground">{t?.allocationRemaining ?? 'المتبقي للتوزيع'}: </span>
                <span className={cn(Math.abs(allocationDelta) <= 0.01 ? 'text-green-600' : 'text-amber-600')}>
                  {formatCurrency(allocationDelta, currencySymbol)}
                </span>
              </div>
              
              <div className="text-xs">
                <span className="text-muted-foreground">{t?.fxLiveTotal ?? 'إجمالي فرق الصرف (مباشر)'}: </span>
                <span className={cn(Math.abs(liveTotalFxDifferenceBase) <= 0.0001 ? 'text-muted-foreground' : liveTotalFxDifferenceBase > 0 ? 'text-amber-600' : 'text-emerald-600')}>
                  {Math.abs(liveTotalFxDifferenceBase) <= 0.0001
                    ? (t?.fxNeutral ?? 'محايد')
                    : `${liveTotalFxDifferenceBase > 0 ? (t?.fxLoss ?? 'خسارة') : (t?.fxGain ?? 'ربح')} ${formatCurrency(Math.abs(liveTotalFxDifferenceBase), currencySymbol)}`}
                </span>
              </div>

              <div className="text-sm text-muted-foreground">
                {t?.allocatedTotal ?? 'إجمالي التوزيع'}: {formatCurrency(totalAllocatedInPaymentCurrency, currencySymbol)}
              </div>

              {selectedSupplierOrders.length === 0 && (
                <p className="text-xs text-muted-foreground">{t?.noOpenInvoices ?? 'لا توجد فواتير مفتوحة لهذا المورد.'}</p>
              )}

              {selectedSupplierOrders.length > 0 && (
                <div className="border rounded-lg overflow-x-auto">
                  <Table className="min-w-[1550px]">
                    <TableHeader>
                      <TableRow>
                        <TableHead>{t?.select ?? 'تحديد'}</TableHead>
                        <TableHead>{t?.invoice ?? 'الفاتورة'}</TableHead>
                        <TableHead>{t?.date ?? 'التاريخ'}</TableHead>
                        <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                        <TableHead>{t?.amountDue ?? 'المبلغ المتبقي'}</TableHead>
                        <TableHead>{t?.allocation ?? 'التوزيع'}</TableHead>
                        <TableHead>{t?.equivalentInPaymentCurrency ?? `المعادل (${watchedCurrency || baseCurrencyCode})`}</TableHead>
                        <TableHead>{t?.invoiceRateCaptured ?? `سعر الفاتورة (${baseCurrencyCode})`}</TableHead>
                        <TableHead>{t?.baseAtInvoiceRate ?? 'القيمة بالأساس وقت الفاتورة'}</TableHead>
                        <TableHead>{t?.baseAtPaymentRate ?? 'القيمة بالأساس وقت الدفع'}</TableHead>
                        <TableHead>{t?.fxDifference ?? 'فرق الصرف'}</TableHead>
                        <TableHead>{t?.match ?? 'المطابقة'}</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {selectedSupplierOrders.map((order) => {
                        const allocation = allocations.find((a) => a.purchaseOrderId === order.id);
                        const due = Number(order.amountDue || 0);
                        const allocAmount = Number(allocation?.amount || 0);
                        const invoiceCurrency = order.currencyCode || baseCurrencyCode;
                        const invoiceRate = Number(getCapturedInvoiceRate(order));
                        const equivalentInPaymentCurrency = convertAmountBetweenCurrencies(allocAmount, invoiceCurrency, watchedCurrency || baseCurrencyCode);
                        const analysisAmount = allocAmount > 0 ? allocAmount : 0;
                        const analysisEquivalentInPaymentCurrency = convertAmountBetweenCurrencies(analysisAmount, invoiceCurrency, watchedCurrency || baseCurrencyCode);
                        // baseAtInvoiceRate: convert invoice currency to base (ILS) using captured rate
                        // if invoiceCurrency === ILS, use as-is; otherwise divide by rate (rate = units per ILS)
                        const baseAtInvoiceRate = invoiceCurrency === baseCurrencyCode 
                          ? analysisAmount 
                          : analysisAmount / (Number.isFinite(invoiceRate) && invoiceRate > 0 ? invoiceRate : 1);
                        const baseAtPaymentRate = (watchedCurrency || baseCurrencyCode) === baseCurrencyCode
                          ? analysisEquivalentInPaymentCurrency
                          : analysisEquivalentInPaymentCurrency / (Number.isFinite(paymentExchangeRateEffective) && paymentExchangeRateEffective > 0 ? paymentExchangeRateEffective : 1);
                        const rowFxDifference = baseAtPaymentRate - baseAtInvoiceRate;
                        const rowDelta = Number((due - allocAmount).toFixed(2));
                        return (
                          <TableRow key={order.id}>
                            <TableCell>
                              <Checkbox
                                checked={selectedInvoiceIds.includes(order.id)}
                                onCheckedChange={(checked) => handleInvoiceSelectionChange(order, checked === true)}
                                disabled={watchedIsAdvance}
                              />
                            </TableCell>
                            <TableCell className="font-medium">{order.orderNumber || order.id}</TableCell>
                            <TableCell>{format(new Date(order.date), 'yyyy-MM-dd')}</TableCell>
                            <TableCell>{order.currencyCode || baseCurrencyCode}</TableCell>
                            <TableCell>{formatCurrency(order.amountDue || 0, order.currencyCode === baseCurrencyCode ? currencySymbol : order.currencyCode || currencySymbol)}</TableCell>
                            <TableCell>
                              <Input
                                type="number"
                                step="0.01"
                                min="0"
                                value={allocation?.amount ?? ''}
                                onChange={(e) => handleAllocationChange(order.id, Number(e.target.value))}
                                disabled={watchedIsAdvance}
                              />
                            </TableCell>
                                <TableCell>
                                  <Input type="number" readOnly disabled value={allocAmount > 0 ? equivalentInPaymentCurrency.toFixed(2) : ''} />
                                </TableCell>
                                <TableCell>{Number.isFinite(invoiceRate) ? invoiceRate.toFixed(4) : '0.0000'}</TableCell>
                                <TableCell className="text-right">{formatCurrency(baseAtInvoiceRate, currencySymbol)}</TableCell>
                                <TableCell className="text-right">{formatCurrency(baseAtPaymentRate, currencySymbol)}</TableCell>
                                <TableCell>
                                  {allocAmount <= 0 || Math.abs(rowFxDifference) <= 0.0001
                                    ? <Badge variant="secondary">{t?.fxNeutral ?? 'محايد'}</Badge>
                                    : (
                                      <Badge variant={rowFxDifference > 0 ? 'default' : 'destructive'}>
                                        {rowFxDifference > 0 ? (t?.fxLoss ?? 'خسارة') : (t?.fxGain ?? 'ربح')} {formatCurrency(Math.abs(rowFxDifference), currencySymbol)}
                                      </Badge>
                                    )}
                                </TableCell>
                                <TableCell>
                                  <Badge variant={Math.abs(rowDelta) <= 0.01 ? 'default' : 'secondary'}>
                                    {Math.abs(rowDelta) <= 0.01
                                      ? (t?.fullyMatched ?? 'مطابق بالكامل')
                                      : `${t?.remaining ?? 'متبقي'} ${formatCurrency(rowDelta, order.currencyCode === baseCurrencyCode ? currencySymbol : order.currencyCode || currencySymbol)}`}
                                  </Badge>
                                </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
              )}
            </div>

            {/* Check Details Section - Show when payment method is 'check' */}
            {form.watch('paymentMethod') === 'check' && (
              <>
                <Separator />
                <div className="space-y-4">
                  <h3 className="font-semibold text-sm">{t?.checkDetails ?? 'تفاصيل الشيك'}</h3>

                  <FormField
                    control={form.control}
                    name="checkSource"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.checkSource ?? 'مصدر الشيك'}</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value || 'issued'}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="issued">{t?.companyChecks ?? 'شيكات الشركة (صادرة)'}</SelectItem>
                            <SelectItem value="incoming">{t?.incomingChecksSource ?? 'شيكات العملاء الواردة'}</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {watchedCheckSource === 'incoming' && (
                    <div className="space-y-2 rounded-md border p-3">
                      <div className="text-sm font-medium">{t?.selectIncomingChecks ?? 'اختر من صندوق الشيكات الواردة'}</div>
                      <div className="text-xs">
                        <span className="text-muted-foreground">{t?.selectedIncomingChecksTotal ?? 'إجمالي الشيكات المختارة'}: </span>
                        <span className="font-medium">{formatCurrency(selectedIncomingChecksTotalInPaymentCurrency, currencySymbol)}</span>
                      </div>
                      <div className="text-xs">
                        <span className="text-muted-foreground">{t?.differenceWithVoucherAmount ?? 'الفرق مع مبلغ السند'}: </span>
                        <span className={cn(Math.abs(incomingChecksSelectionDelta) <= 0.01 ? 'text-green-600' : 'text-amber-600')}>
                          {formatCurrency(incomingChecksSelectionDelta, currencySymbol)}
                        </span>
                      </div>
                      {availableIncomingChecks.length === 0 ? (
                        <div className="text-xs text-muted-foreground">{t?.noIncomingChecksAvailable ?? 'لا توجد شيكات واردة متاحة حالياً.'}</div>
                      ) : (
                        <div className="max-h-64 overflow-auto rounded-md border">
                          <Table>
                            <TableHeader>
                              <TableRow>
                                <TableHead>{t?.select ?? 'تحديد'}</TableHead>
                                <TableHead>{t?.checkNumber ?? 'رقم الشيك'}</TableHead>
                                <TableHead>{t?.customerName ?? 'العميل'}</TableHead>
                                <TableHead>{t?.bankName ?? 'البنك'}</TableHead>
                                <TableHead className="text-right">{t?.amount ?? 'المبلغ'}</TableHead>
                                <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {availableIncomingChecks.map((incomingCheck) => (
                                <TableRow key={incomingCheck.id}>
                                  <TableCell>
                                    <Checkbox
                                      checked={selectedIncomingCheckIds.includes(incomingCheck.id)}
                                      onCheckedChange={(checked) => {
                                        const next = checked === true
                                          ? Array.from(new Set([...selectedIncomingCheckIds, incomingCheck.id]))
                                          : selectedIncomingCheckIds.filter((id) => id !== incomingCheck.id);

                                        const nextTotal = availableIncomingChecks
                                          .filter((entry) => next.includes(entry.id))
                                          .reduce((sum, entry) => {
                                            const checkCurrency = entry.currency || baseCurrencyCode;
                                            return sum + convertAmountBetweenCurrencies(Number(entry.amount || 0), checkCurrency, watchedCurrency || baseCurrencyCode);
                                          }, 0);

                                        setSelectedIncomingCheckIds(next);
                                        form.setValue('incomingCheckIds', next, { shouldDirty: true, shouldValidate: true });

                                        if (next.length > 0) {
                                          const confirmed = typeof window !== 'undefined'
                                            ? window.confirm(t?.syncAmountWithSelectedIncomingChecks ?? 'هل تريد تحديث مبلغ السند ليتطابق مع مجموع الشيكات المختارة؟')
                                            : false;
                                          if (confirmed) {
                                            form.setValue('amount', Number(nextTotal.toFixed(2)), { shouldDirty: true, shouldValidate: true });
                                          }
                                        }
                                      }}
                                    />
                                  </TableCell>
                                  <TableCell className="font-medium">{incomingCheck.checkNumber}</TableCell>
                                  <TableCell>{incomingCheck.customerName}</TableCell>
                                  <TableCell>{incomingCheck.bankName}</TableCell>
                                  <TableCell className="text-right">{formatCurrency(incomingCheck.amount || 0, currencySymbol)}</TableCell>
                                  <TableCell>{incomingCheck.currency}</TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      )}
                    </div>
                  )}

                  {/* Checks Table */}
                  {watchedCheckSource !== 'incoming' && checks.length > 0 && (
                    <div className="border rounded-lg overflow-hidden">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>{t?.checkNumber ?? 'رقم الشيك'}</TableHead>
                            <TableHead>{t?.bankName ?? 'اسم البنك'}</TableHead>
                            <TableHead>{t?.checkDate ?? 'التاريخ'}</TableHead>
                            <TableHead className="text-right">{t?.amount ?? 'المبلغ'}</TableHead>
                            <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                            <TableHead className="w-10 text-center">{t?.actions ?? 'إجراءات'}</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {checks.map((check) => (
                            <TableRow key={check.id}>
                              <TableCell className="font-medium">{check.checkNumber}</TableCell>
                              <TableCell>{check.bankName}</TableCell>
                              <TableCell>{format(new Date(check.checkDate), 'dd/MM/yyyy')}</TableCell>
                              <TableCell className="text-right">{formatCurrency(check.amount || 0, currencySymbol)}</TableCell>
                              <TableCell>{check.currency}</TableCell>
                              <TableCell className="text-center">
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="icon"
                                  onClick={() => handleRemoveCheck(check.id)}
                                  className="h-8 w-8"
                                >
                                  <X className="h-4 w-4" />
                                </Button>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  )}

                  {/* Add Check Form */}
                  {watchedCheckSource !== 'incoming' && !showCheckForm && (
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setShowCheckForm(true)}
                      className="w-full"
                    >
                      {t?.addCheck ?? '+ إضافة شيك'}
                    </Button>
                  )}

                  {watchedCheckSource !== 'incoming' && showCheckForm && (
                    <div className="border rounded-lg overflow-hidden">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>{t?.checkNumber ?? 'رقم الشيك'} *</TableHead>
                            <TableHead>{t?.bankName ?? 'اسم البنك'} *</TableHead>
                            <TableHead>{t?.checkDate ?? 'تاريخ الشيك'} *</TableHead>
                            <TableHead>{t?.amount ?? 'المبلغ'} *</TableHead>
                            <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                            <TableHead className="w-24 text-center">{t?.actions ?? 'إجراءات'}</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          <TableRow>
                            <Form {...checkForm}>
                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="checkNumber"
                                  render={({ field }) => (
                                    <FormItem>
                                      <FormControl>
                                        <Input
                                          placeholder={t?.checkNumberPlaceholder ?? 'مثال: CHK-001234'}
                                          {...field}
                                          className="h-8"
                                        />
                                      </FormControl>
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  )}
                                />
                              </TableCell>

                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="bankId"
                                  render={({ field }) => (
                                    <FormItem>
                                      <div className="flex items-center gap-2">
                                        <Select
                                          onValueChange={(bankId) => {
                                            if (bankId === '__add_bank__') {
                                              setIsAddBankDialogOpen(true);
                                              return;
                                            }
                                            field.onChange(bankId);
                                            const selectedBank = bankOptions.find((bank) => bank.id === bankId);
                                            if (selectedBank?.currencyCode) {
                                              checkForm.setValue('currency', selectedBank.currencyCode, { shouldValidate: true });
                                            }
                                          }}
                                          defaultValue={field.value}
                                        >
                                          <FormControl>
                                            <SelectTrigger className="h-8 w-full">
                                              <SelectValue placeholder={t?.selectBank ?? 'اختر بنك'} />
                                            </SelectTrigger>
                                          </FormControl>
                                          <SelectContent>
                                            {bankOptions.map((bank) => (
                                              <SelectItem key={bank.id} value={bank.id}>
                                                {bank.fullName || bank.name} {bank.branch ? `- ${bank.branch}` : ''}
                                              </SelectItem>
                                            ))}
                                            <Separator className="my-1" />
                                            <SelectItem value="__add_bank__" className="flex items-center justify-center gap-2 py-2 text-center text-xs font-medium text-blue-600 hover:text-blue-700">
                                              <Plus className="h-3 w-3" />
                                              {t?.addBank || 'إضافة بنك'}
                                            </SelectItem>
                                          </SelectContent>
                                        </Select>
                                      </div>
                                      <AddBankDialog
                                        isOpen={isAddBankDialogOpen}
                                        onOpenChange={setIsAddBankDialogOpen}
                                        currencies={currencyOptions}
                                        accountOptions={[]}
                                        t={t}
                                        tGlobal={tGlobal}
                                        onBankAdded={(newBank) => {
                                          setBankOptions((prev) => [...prev, newBank]);
                                          checkForm.setValue('bankId', newBank.id, { shouldValidate: true });
                                          if (newBank.currencyCode) {
                                            checkForm.setValue('currency', newBank.currencyCode, { shouldValidate: true });
                                          }
                                        }}
                                      />
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  )}
                                />
                              </TableCell>

                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="checkDate"
                                  render={({ field }) => (
                                    <FormItem>
                                      <FormControl>
                                        <Input
                                          type="date"
                                          {...field}
                                          className="h-8"
                                        />
                                      </FormControl>
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  )}
                                />
                              </TableCell>

                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="amount"
                                  render={({ field }) => (
                                    <FormItem>
                                      <FormControl>
                                        <Input
                                          type="number"
                                          step="0.01"
                                          min="0"
                                          {...field}
                                          className="h-8"
                                        />
                                      </FormControl>
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  )}
                                />
                              </TableCell>

                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="currency"
                                  render={({ field }) => {
                                    const selectedCurrency = currencyOptions.find(c => c.code === field.value);
                                    return (
                                    <FormItem>
                                      <Select onValueChange={field.onChange} value={field.value}>
                                        <FormControl>
                                          <SelectTrigger className="h-8 w-full">
                                            <SelectValue>
                                              {selectedCurrency ? `${selectedCurrency.code} - ${selectedCurrency.symbol}` : t?.currency ?? 'العملة'}
                                            </SelectValue>
                                          </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                          {currencyOptions.map((currency) => (
                                            <SelectItem key={currency.code} value={currency.code}>
                                              {currency.code} - {currency.name} ({currency.symbol})
                                            </SelectItem>
                                          ))}
                                        </SelectContent>
                                      </Select>
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  );
                                  }}
                                />
                              </TableCell>

                              <TableCell className="text-center">
                                <div className="flex gap-1 justify-center">
                                  <Button
                                    type="button"
                                    size="icon"
                                    onClick={() => checkForm.handleSubmit(handleAddCheck)()}
                                    className="h-8 w-8"
                                    title={t?.addCheck ?? 'إضافة شيك'}
                                  >
                                    <Plus className="h-4 w-4" />
                                  </Button>
                                  <Button
                                    type="button"
                                    variant="outline"
                                    size="icon"
                                    onClick={() => setShowCheckForm(false)}
                                    className="h-8 w-8"
                                    title={tGlobal?.cancel ?? 'إلغاء'}
                                  >
                                    <X className="h-4 w-4" />
                                  </Button>
                                </div>
                              </TableCell>
                            </Form>
                          </TableRow>
                        </TableBody>
                      </Table>
                    </div>
                  )}
                </div>
              </>
            )}

            {/* Notes */}
            <FormField
              control={form.control}
              name="notes"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.notes ?? 'ملاحظات'}</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Additional notes..."
                      className="resize-none"
                      rows={3}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </CardContent>

          <div className="p-6 pt-0 space-y-2">
            {editingInCreatePaymentId && <DocumentLockBanner lockStatus={createEditLockStatus} />}
            {editingInCreatePaymentId && (
              <Button
                type="button"
                variant="ghost"
                className="w-full"
                disabled={isPending}
                onClick={() => {
                  setEditingInCreatePaymentId(null);
                  router.replace('/admin/purchases/payment');
                  form.reset({
                    supplierId: '',
                    amount: 0,
                    paymentMethod: 'cash',
                    reference: '',
                    notes: '',
                    currencyCode: baseCurrencyCode,
                    exchangeRate: 1,
                    rateDate: format(new Date(), 'yyyy-MM-dd'),
                    isAdvance: false,
                    postingStatus: 'posted',
                    allocationMode: 'manual',
                    checks: [],
                  });
                  setAllocations([]);
                  setSelectedInvoiceIds([]);
                  setSelectedIncomingCheckIds([]);
                }}
              >
                {t?.cancelEditMode ?? 'إلغاء وضع التعديل والعودة إلى إنشاء جديد'}
              </Button>
            )}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-2">
              <Button 
                type="button" 
                variant="outline"
                className="w-full" 
                disabled={isPending || isCreateEditLocked} 
                onClick={() => handleCreateSubmitWithStatus('draft')}
              >
                {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                {t?.saveAsDraft ?? 'حفظ كمسودة'}
              </Button>
              <Button 
                type="button" 
                variant="secondary"
                className="w-full" 
                disabled={isPending || isCreateEditLocked} 
                onClick={() => handleCreateSubmitWithStatus('saved')}
              >
                {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                {t?.saveOnly ?? 'حفظ بدون ترحيل'} <span className="ms-2 text-xs opacity-75">(F2)</span>
              </Button>
              <Button 
                type="button" 
                className="w-full" 
                disabled={isPending || isCreateEditLocked} 
                onClick={() => handleCreateSubmitWithStatus('posted')}
              >
                {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                {t?.recordAndPost ?? 'تسجيل وترحيل'}
              </Button>
            </div>
            <div className="text-xs text-muted-foreground">
              {t?.postingByActionHint ?? 'يتم تحديد حالة السند حسب الزر الذي تختاره. اضغط F2 للحفظ السريع (بدون ترحيل).'}
            </div>
          </div>
        </form>
      </Form>
    </Card>
    </TabsContent>

    <TabsContent value="list" className="mt-4">
    <Card className="border shadow-sm">
      <CardHeader>
        <CardTitle>{t?.registeredVouchers ?? 'تفاصيل السندات المسجلة'}</CardTitle>
        <CardDescription>{t?.registeredVouchersDescription ?? 'استعرض السندات المسجلة مع حالة الترحيل وفروقات الصرف والإجراءات المتاحة.'}</CardDescription>
      </CardHeader>
      <CardContent>
        {paymentRows.length === 0 ? (
          <div className="text-sm text-muted-foreground">{t?.noVouchersYet ?? 'لا توجد سندات دفع مسجلة بعد.'}</div>
        ) : (
          <div className="relative w-full overflow-auto rounded-md border">
            <Table className="min-w-[1450px]">
              <TableHeader>
                <TableRow>
                  <TableHead>{t?.voucherNumber ?? 'رقم السند'}</TableHead>
                  <TableHead>{t?.date ?? 'التاريخ'}</TableHead>
                  <TableHead>{t?.supplierName ?? 'اسم المورد'}</TableHead>
                  <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                  <TableHead className="text-right">{t?.amount ?? 'المبلغ'}</TableHead>
                  <TableHead>{t?.exchangeRate ?? 'سعر الصرف'}</TableHead>
                  <TableHead className="text-right">{t?.convertedToBase ?? 'المبلغ بالعملة الأساسية'}</TableHead>
                  <TableHead>{t?.reference ?? 'المرجع'}</TableHead>
                  <TableHead>{t?.status ?? 'الحالة'}</TableHead>
                  <TableHead>{t?.postingStatus ?? 'مرحلة السند'}</TableHead>
                  <TableHead className="text-right">{t?.fxDifference ?? 'فرق الصرف (ربح/خسارة)'}</TableHead>
                  <TableHead className="text-right">{t?.actions ?? 'إجراءات'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {paymentRows.map((payment) => (
                  <Fragment key={payment.id}>
                  <TableRow>
                    <TableCell className="font-medium">{payment.id}</TableCell>
                    <TableCell>{format(new Date(payment.date), 'yyyy-MM-dd')}</TableCell>
                    <TableCell>{getSupplierNameById(payment.supplierId)}</TableCell>
                    <TableCell>{payment.currencyCode || baseCurrencyCode}</TableCell>
                    <TableCell className="text-right">{formatCurrency(payment.amount || 0, currencySymbol)}</TableCell>
                    <TableCell>{Number(payment.exchangeRate || 1).toFixed(4)}</TableCell>
                    <TableCell className="text-right">{formatCurrency(
                      payment.amountBase ?? (
                        (payment.currencyCode || baseCurrencyCode) === baseCurrencyCode
                          ? Number(payment.amount || 0)
                          : Number(payment.amount || 0) / (Number(payment.exchangeRate || 1) > 0 ? Number(payment.exchangeRate || 1) : 1)
                      ),
                      currencySymbol,
                    )}</TableCell>
                    <TableCell>{(payment.reference || '').trim() || '-'}</TableCell>
                    <TableCell>
                      {payment.status === 'cancelled'
                        ? <Badge variant="destructive">{t?.statusCancelled ?? 'ملغى'}</Badge>
                        : <Badge variant="default">{t?.statusActive ?? 'نشط'}</Badge>}
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">
                        {payment.postingStatus === 'draft'
                          ? (t?.postingDraftShort ?? 'مسودة')
                          : payment.postingStatus === 'saved'
                            ? (t?.postingSavedShort ?? 'محفوظ')
                            : (t?.postingPostedShort ?? 'مرحل')}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      {(() => {
                        const fx = Number(payment.totalFxDifferenceBase || 0);
                        if (Math.abs(fx) <= 0.0001) {
                          return <Badge variant="secondary">{t?.fxNeutral ?? 'محايد'}</Badge>;
                        }
                        return (
                          <Badge variant={fx > 0 ? 'default' : 'destructive'}>
                            {fx > 0 ? (t?.fxLoss ?? 'خسارة') : (t?.fxGain ?? 'ربح')} {formatCurrency(Math.abs(fx), currencySymbol)}
                          </Badge>
                        );
                      })()}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="inline-flex items-center gap-2">
                        <Button type="button" size="sm" variant="outline" onClick={() => setPreviewPayment(payment)}>
                          <Eye className="h-4 w-4" />
                          {t?.preview ?? 'معاينة'}
                        </Button>
                        <Button type="button" size="sm" variant="outline" onClick={() => setExpandedPaymentId((prev) => prev === payment.id ? null : payment.id)}>
                          <ListTree className="h-4 w-4" />
                          {t?.details ?? 'تفاصيل'}
                        </Button>
                        <Button type="button" size="sm" variant="outline" onClick={() => handleStartEditInCreate(payment)} disabled={payment.status === 'cancelled'}>
                          <Pencil className="h-4 w-4" />
                          {t?.edit ?? 'تعديل'}
                        </Button>
                        <Button type="button" size="sm" variant="destructive" onClick={() => handleCancelPayment(payment)} disabled={payment.status === 'cancelled' || isPending}>
                          {t?.cancel ?? 'إلغاء'}
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                  {expandedPaymentId === payment.id && (
                    <TableRow>
                      <TableCell colSpan={12} className="bg-muted/30">
                        <div className="space-y-3 p-2">
                          <div className="font-medium text-sm">{t?.paidInvoices ?? 'الفواتير التي تم تسديدها'}</div>
                          {Array.isArray(payment.allocations) && payment.allocations.length > 0 ? (
                            <div className="rounded-md border overflow-hidden">
                              <Table>
                                <TableHeader>
                                  <TableRow>
                                    <TableHead>{t?.invoice ?? 'الفاتورة'}</TableHead>
                                    <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                                    <TableHead className="text-right">{t?.amount ?? 'المبلغ'}</TableHead>
                                    <TableHead className="text-right">{t?.convertedToBase ?? 'المبلغ بالأساس'}</TableHead>
                                  </TableRow>
                                </TableHeader>
                                <TableBody>
                                  {payment.allocations.map((allocation) => (
                                    <TableRow key={allocation.id}>
                                      <TableCell>{allocation.purchaseOrderNumber || allocation.purchaseOrderId}</TableCell>
                                      <TableCell>{allocation.invoiceCurrencyCode}</TableCell>
                                      <TableCell className="text-right">{formatCurrency(allocation.amount || 0, allocation.invoiceCurrencyCode === baseCurrencyCode ? currencySymbol : (allocation.invoiceCurrencyCode || currencySymbol))}</TableCell>
                                      <TableCell className="text-right">{formatCurrency(allocation.amountBase || 0, currencySymbol)}</TableCell>
                                    </TableRow>
                                  ))}
                                </TableBody>
                              </Table>
                            </div>
                          ) : (
                            <div className="text-sm text-muted-foreground">{payment.isAdvance ? (t?.advancePaymentNoInvoices ?? 'دفعة مقدمة غير مرتبطة بفواتير.') : (t?.noInvoiceAllocations ?? 'لا توجد فواتير مرتبطة بهذا السند.')}</div>
                          )}

                          {payment.notes && (
                            <div className="text-sm"><span className="font-medium">{t?.notes ?? 'ملاحظات'}:</span> {payment.notes}</div>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  )}
                  </Fragment>
                ))}
              </TableBody>
            </Table>
          </div>
        )}
      </CardContent>
    </Card>
    </TabsContent>
    </Tabs>

    <Dialog open={!!previewPayment} onOpenChange={(open) => { if (!open) setPreviewPayment(null); }}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>{t?.preview ?? 'معاينة'} - {previewPayment?.id}</DialogTitle>
          <DialogDescription className="sr-only">{t?.previewPaymentDescription ?? 'معاينة تفاصيل سند الدفع.'}</DialogDescription>
        </DialogHeader>
        {previewPayment && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
            <div><span className="font-medium">{t?.date ?? 'التاريخ'}:</span> {format(new Date(previewPayment.date), 'yyyy-MM-dd')}</div>
            <div><span className="font-medium">{t?.supplierName ?? 'اسم المورد'}:</span> {getSupplierNameById(previewPayment.supplierId)}</div>
            <div><span className="font-medium">{t?.currency ?? 'العملة'}:</span> {previewPayment.currencyCode || baseCurrencyCode}</div>
            <div><span className="font-medium">{t?.exchangeRate ?? 'سعر الصرف'}:</span> {Number(previewPayment.exchangeRate || 1).toFixed(4)}</div>
            <div><span className="font-medium">{t?.amount ?? 'المبلغ'}:</span> {formatCurrency(previewPayment.amount || 0, currencySymbol)}</div>
            <div><span className="font-medium">{t?.convertedToBase ?? 'المبلغ بالعملة الأساسية'}:</span> {formatCurrency(previewPayment.amountBase ?? ((previewPayment.amount || 0) * Number(previewPayment.exchangeRate || 1)), currencySymbol)}</div>
            <div className="md:col-span-2"><span className="font-medium">{t?.reference ?? 'المرجع'}:</span> {(previewPayment.reference || '').trim() || '-'}</div>
            <div className="md:col-span-2"><span className="font-medium">{t?.notes ?? 'ملاحظات'}:</span> {(previewPayment.notes || '').trim() || '-'}</div>
          </div>
        )}
      </DialogContent>
    </Dialog>

    <Dialog open={!!editingPayment} onOpenChange={(open) => { if (!open) setEditingPayment(null); }}>
      <DialogContent className="max-w-xl">
        <DialogHeader>
          <DialogTitle>{t?.edit ?? 'تعديل'} - {editingPayment?.id}</DialogTitle>
          <DialogDescription className="sr-only">{t?.editPaymentDescription ?? 'عدّل تفاصيل سند الدفع ثم احفظ التغييرات.'}</DialogDescription>
        </DialogHeader>
        <Form {...paymentEditForm}>
          <form onSubmit={paymentEditForm.handleSubmit(handleUpdatePaymentFull)} className="space-y-4">
            <DocumentLockBanner lockStatus={modalEditLockStatus} />
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <FormField
                control={paymentEditForm.control}
                name="amount"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.amount ?? 'المبلغ'}</FormLabel>
                    <FormControl><Input type="number" step="0.01" min="0" {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={paymentEditForm.control}
                name="currencyCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.currency ?? 'العملة'}</FormLabel>
                    <Select value={field.value} onValueChange={field.onChange}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {currencyOptions.map((currency) => (
                          <SelectItem key={currency.code} value={currency.code}>{currency.code} - {currency.name}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={paymentEditForm.control}
                name="exchangeRate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.exchangeRate ?? 'سعر الصرف'}</FormLabel>
                    <FormControl><Input type="number" step="0.0001" min="0" {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={paymentEditForm.control}
              name="rateDate"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.rateDate ?? 'تاريخ السعر'}</FormLabel>
                  <FormControl><Input type="date" {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={paymentEditForm.control}
              name="postingStatus"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.postingStatus ?? 'مرحلة السند'}</FormLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="draft">{t?.postingDraft ?? 'مسودة (بدون أثر)'}</SelectItem>
                      <SelectItem value="saved">{t?.postingSaved ?? 'محفوظ (أثر تشغيلي فقط)'}</SelectItem>
                      <SelectItem value="posted">{t?.postingPosted ?? 'مرحل (أثر تشغيلي ومحاسبي)'}</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={paymentEditForm.control}
              name="isAdvance"
              render={({ field }) => (
                <FormItem className="flex items-center justify-between rounded-md border px-3 py-2">
                  <FormLabel>{t?.advanceToggle ?? 'دفعة مقدمة'}</FormLabel>
                  <FormControl><Switch checked={field.value} onCheckedChange={field.onChange} /></FormControl>
                </FormItem>
              )}
            />

            <FormField
              control={paymentEditForm.control}
              name="reference"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.reference ?? 'المرجع'}</FormLabel>
                  <FormControl><Input {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={paymentEditForm.control}
              name="notes"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.notes ?? 'ملاحظات'}</FormLabel>
                  <FormControl><Textarea rows={3} {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="space-y-2 rounded-md border p-3">
              <div className="text-sm font-medium">{t?.allocations ?? 'توزيع الدفعة على الفواتير'}</div>
              {editableOrders.length === 0 ? (
                <div className="text-xs text-muted-foreground">{t?.noOpenInvoices ?? 'لا توجد فواتير متاحة.'}</div>
              ) : (
                <div className="rounded-md border overflow-hidden">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>{t?.invoice ?? 'الفاتورة'}</TableHead>
                        <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                        <TableHead className="text-right">{t?.amountDue ?? 'المتبقي'}</TableHead>
                        <TableHead>{t?.allocation ?? 'التوزيع'}</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {editableOrders.map((order) => {
                        const currentFromThisPayment = Number((editingPayment?.allocations || []).find((entry) => entry.purchaseOrderId === order.id)?.amount || 0);
                        const availableForEdit = Number(order.amountDue || 0) + currentFromThisPayment;
                        const currentEditAllocation = Number(editAllocations.find((entry) => entry.purchaseOrderId === order.id)?.amount || 0);
                        return (
                          <TableRow key={order.id}>
                            <TableCell>{order.orderNumber || order.id}</TableCell>
                            <TableCell>{order.currencyCode || baseCurrencyCode}</TableCell>
                            <TableCell className="text-right">{formatCurrency(availableForEdit, currencySymbol)}</TableCell>
                            <TableCell>
                              <Input
                                type="number"
                                step="0.01"
                                min="0"
                                max={Math.max(0, availableForEdit)}
                                value={currentEditAllocation || ''}
                                onChange={(event) => handleEditAllocationChange(order.id, Number(event.target.value))}
                                disabled={editIsAdvance === true || ((order.currencyCode || baseCurrencyCode) !== (editCurrencyCode || baseCurrencyCode))}
                              />
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
              )}
              {editIsAdvance !== true && (
                <div className="text-xs text-muted-foreground">
                  {t?.allocationMustMatch ?? 'مجموع التوزيع يجب أن يساوي مبلغ الدفعة'}
                </div>
              )}
            </div>

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setEditingPayment(null)}>{tGlobal?.cancel ?? 'إلغاء'}</Button>
              <Button type="submit" disabled={isPending || isModalEditLocked}>{t?.save ?? 'حفظ'}</Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
    </div>
  );
}
