
'use client';

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

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
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 { Separator } from '@/components/ui/separator';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Loader2, PlusCircle, Trash2, Maximize2, Minimize2, Settings } from 'lucide-react';
import { type Customer, type ProductionItem, type CustomerPricing, type SalesRep, type Supplier, type ItemGroup, type CustomerCategory, type Warehouse } from '@/lib/types';
import { useToast } from '@/hooks/use-toast';
import dynamic from 'next/dynamic';
import { handleCreateSaleInvoice } from '@/lib/actions';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { InvoiceTabsNav, PartySelector } from '@/components/invoice-shared';
import { cn } from '@/lib/utils';
import { formatCurrency } from '@/lib/currency-formatter';
import { MaterialItemDialog } from '@/components/admin/list-manager';
import { PaymentMethodModal } from '@/components/admin/payment-method-modal';
import type { PaymentBreakdown } from '@/lib/types';
const AddCustomerDialog = dynamic(() => import('./add-customer-dialog'), { ssr: false });

const saleInvoiceSchema = z.object({
  customerId: z.string().optional().default(''),
  manualDocNumber: z.string().optional().default(''),
  notes: z.string().optional().default(''),
  discountAmount: z.coerce.number().min(0).default(0),
  items: z.array(z.object({
    materialId: z.string().min(1, 'Please select an item.'),
    quantity: z.coerce.number().min(1, 'Quantity must be at least 1.'),
    unitPrice: z.coerce.number().min(0, 'Price must be a positive number.'),
    description: z.string().optional().default(''),
    discount: z.coerce.number().min(0).default(0),
    warehouseId: z.string().optional().default(''),
    shelfId: z.string().optional().default(''),
  })).min(1, 'Please add at least one item to the invoice.'),
});

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

type SalesInvoiceFormProps = {
  customers: Customer[];
  suppliers: Supplier[];
  materials: ProductionItem[];
  itemGroups?: ItemGroup[];
  categories?: CustomerCategory[];
  allCustomerPricing: CustomerPricing[];
  salesReps?: SalesRep[];
  t: any;
  tGlobal: any;
  currencySymbol?: string;
  warehouses?: Warehouse[];
  warehouseConfig?: {
    enabled: boolean;
    defaultWarehouseId?: string;
    defaultShelfId?: string;
  };
};

type InvoiceColumnId =
  | 'lineNo'
  | 'material'
  | 'itemNumber'
  | 'description'
  | 'barcode'
  | 'unit'
  | 'warehouse'
  | 'shelf'
  | 'quantity'
  | 'unitPrice'
  | 'discount'
  | 'bonus'
  | 'total'
  | 'actions';

type InvoiceColumnDef = {
  id: InvoiceColumnId;
  label: string;
  defaultWidth: number;
  minWidth?: number;
  canHide?: boolean;
  canMove?: boolean;
};

export default function SalesInvoiceForm({ customers, suppliers, materials, itemGroups = [], categories = [], allCustomerPricing, salesReps = [], t, tGlobal, currencySymbol = '$', warehouses = [], warehouseConfig }: SalesInvoiceFormProps) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const [selectedPartyId, setSelectedPartyId] = useState<string>('');
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [barcodeInput, setBarcodeInput] = useState("");
  const [invoiceDateLabel, setInvoiceDateLabel] = useState('');
  const [showAddMaterialDialog, setShowAddMaterialDialog] = useState(false);
  const [addMaterialInitialValues, setAddMaterialInitialValues] = useState<Partial<ProductionItem> | undefined>(undefined);
  const [extraMaterials, setExtraMaterials] = useState<ProductionItem[]>([]);
  const [showWeightDialog, setShowWeightDialog] = useState(false);
  const [weightInput, setWeightInput] = useState("");
  const [pendingWeightMaterial, setPendingWeightMaterial] = useState<ProductionItem | null>(null);
  const [pendingWeightUnitPrice, setPendingWeightUnitPrice] = useState(0);
  const [pendingWeightPrimaryPrice, setPendingWeightPrimaryPrice] = useState(0);
  const [pendingWeightDescription, setPendingWeightDescription] = useState('');
  const [pendingMeasurementMode, setPendingMeasurementMode] = useState<'weight' | 'volume'>('weight');
  const [pendingVolumeOptions, setPendingVolumeOptions] = useState<Array<{ key: string; label: string; price: number }>>([]);
  const [selectedVolumeOptionKey, setSelectedVolumeOptionKey] = useState('');
  const [showAddCustomerDialog, setShowAddCustomerDialog] = useState(false);
  const [showItemPicker, setShowItemPicker] = useState(false);
  const [paymentModalOpen, setPaymentModalOpen] = useState(false);
  const [payments, setPayments] = useState<PaymentBreakdown[]>([]);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [customerList, setCustomerList] = useState(customers);
  const [supplierList, setSupplierList] = useState(suppliers);
  const [itemSelectQuery, setItemSelectQuery] = useState('');
  const [itemPickerQuery, setItemPickerQuery] = useState('');
  const [itemSelectInputResetKey, setItemSelectInputResetKey] = useState(0);
  const [itemPickerInputResetKey, setItemPickerInputResetKey] = useState(0);
  const itemPickerInputRef = useRef<HTMLInputElement | null>(null);
  const editableGridRef = useRef<HTMLDivElement | null>(null);
  const isWarehouseEnabled = warehouseConfig?.enabled === true;
  const defaultWarehouseId = isWarehouseEnabled ? warehouseConfig?.defaultWarehouseId || '' : '';
  const defaultShelfId = isWarehouseEnabled ? warehouseConfig?.defaultShelfId || '' : '';
  const shelvesByWarehouse = useMemo(() => {
    const map = new Map<string, { id: string; name: string }[]>();
    warehouses.forEach((warehouse) => {
      map.set(warehouse.id, Array.isArray(warehouse.shelves) ? warehouse.shelves : []);
    });
    return map;
  }, [warehouses]);

  const form = useForm<z.infer<typeof saleInvoiceSchema>>({
    resolver: zodResolver(saleInvoiceSchema),
    defaultValues: {
      customerId: '',
      discountAmount: 0,
      items: [],
    },
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: 'items',
  });

  const [columnOrder, setColumnOrder] = useState<InvoiceColumnId[]>([]);
  const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>({});
  const [columnWidths, setColumnWidths] = useState<Record<string, number>>({});
  const [columnSettingsOpen, setColumnSettingsOpen] = useState(false);

  const allColumnDefs = useMemo<InvoiceColumnDef[]>(() => {
    const defs: InvoiceColumnDef[] = [
      { id: 'lineNo', label: '#', defaultWidth: 56, minWidth: 52, canHide: false, canMove: false },
      { id: 'material', label: t?.item ?? 'الصنف', defaultWidth: 260, minWidth: 220, canHide: false },
      { id: 'itemNumber', label: t?.itemNumberLabel ?? 'رقم الصنف', defaultWidth: 110, minWidth: 90 },
      { id: 'description', label: t?.descriptionLabel ?? 'الوصف', defaultWidth: 220, minWidth: 170 },
      { id: 'barcode', label: t?.barcodeLabel ?? 'الباركود', defaultWidth: 130, minWidth: 100 },
      { id: 'unit', label: t?.unitLabel ?? 'الوحدة', defaultWidth: 100, minWidth: 90 },
    ];

    if (isWarehouseEnabled) {
      defs.push(
        { id: 'warehouse', label: t?.warehouseLabel ?? 'المستودع', defaultWidth: 170, minWidth: 130 },
        { id: 'shelf', label: t?.shelfLabel ?? 'الرف', defaultWidth: 140, minWidth: 110 }
      );
    }

    defs.push(
      { id: 'quantity', label: t?.quantity ?? 'الكمية', defaultWidth: 120, minWidth: 100 },
      { id: 'unitPrice', label: t?.price ?? 'السعر', defaultWidth: 130, minWidth: 110 },
      { id: 'discount', label: t?.itemDiscountLabel ?? 'خصم الصنف', defaultWidth: 150, minWidth: 120 },
      { id: 'bonus', label: t?.bonus ?? 'بونص', defaultWidth: 90, minWidth: 80 },
      { id: 'total', label: t?.total ?? 'الإجمالي', defaultWidth: 120, minWidth: 110 },
      { id: 'actions', label: '', defaultWidth: 64, minWidth: 56, canHide: false }
    );

    return defs;
  }, [isWarehouseEnabled, t]);

  const layoutStorageKey = useMemo(
    () => `salesInvoiceGridLayout-v2-${isWarehouseEnabled ? 'wh' : 'basic'}`,
    [isWarehouseEnabled]
  );

  useEffect(() => {
    const defaultOrder = allColumnDefs.map((column) => column.id);
    const defaultVisibility = Object.fromEntries(allColumnDefs.map((column) => [column.id, true]));
    const defaultWidths = Object.fromEntries(allColumnDefs.map((column) => [column.id, column.defaultWidth]));

    const raw = localStorage.getItem(layoutStorageKey);
    if (!raw) {
      setColumnOrder(defaultOrder);
      setColumnVisibility(defaultVisibility);
      setColumnWidths(defaultWidths);
      return;
    }

    try {
      const parsed = JSON.parse(raw) as {
        order?: InvoiceColumnId[];
        visibility?: Record<string, boolean>;
        widths?: Record<string, number>;
      };

      const availableSet = new Set(defaultOrder);
      const parsedOrder = Array.isArray(parsed.order)
        ? parsed.order.filter((id) => availableSet.has(id))
        : [];
      const finalOrder = [...parsedOrder, ...defaultOrder.filter((id) => !parsedOrder.includes(id))];

      const visibility = { ...defaultVisibility, ...(parsed.visibility || {}) };
      allColumnDefs.forEach((column) => {
        if (column.canHide === false) {
          visibility[column.id] = true;
        }
      });

      const widths = { ...defaultWidths };
      Object.entries(parsed.widths || {}).forEach(([id, width]) => {
        const column = allColumnDefs.find((entry) => entry.id === id);
        const numericWidth = Number(width || 0);
        if (!column || !Number.isFinite(numericWidth)) return;
        widths[id] = Math.max(column.minWidth || 80, numericWidth);
      });

      setColumnOrder(finalOrder);
      setColumnVisibility(visibility);
      setColumnWidths(widths);
    } catch {
      setColumnOrder(defaultOrder);
      setColumnVisibility(defaultVisibility);
      setColumnWidths(defaultWidths);
    }
  }, [allColumnDefs, layoutStorageKey]);

  useEffect(() => {
    if (columnOrder.length === 0) return;
    localStorage.setItem(
      layoutStorageKey,
      JSON.stringify({
        order: columnOrder,
        visibility: columnVisibility,
        widths: columnWidths,
      })
    );
  }, [columnOrder, columnVisibility, columnWidths, layoutStorageKey]);

  const columnDefById = useMemo(() => {
    const map = new Map<InvoiceColumnId, InvoiceColumnDef>();
    allColumnDefs.forEach((column) => map.set(column.id, column));
    return map;
  }, [allColumnDefs]);

  const orderedVisibleColumns = useMemo(() => {
    if (columnOrder.length === 0) return allColumnDefs;
    return columnOrder
      .map((id) => columnDefById.get(id))
      .filter((column): column is InvoiceColumnDef => !!column)
      .filter((column) => columnVisibility[column.id] !== false);
  }, [columnOrder, columnDefById, columnVisibility, allColumnDefs]);

  const editableColumnIds = useMemo(
    () => orderedVisibleColumns
      .map((column) => column.id)
      .filter((id) => ['material', 'description', 'warehouse', 'shelf', 'quantity', 'unitPrice', 'discount'].includes(id)),
    [orderedVisibleColumns]
  );

  const gridColumnIndex = useMemo(() => {
    const indexByColumn: Partial<Record<InvoiceColumnId, number>> = {};
    editableColumnIds.forEach((id, index) => {
      indexByColumn[id] = index;
    });
    return indexByColumn;
  }, [editableColumnIds]);

  const handleGridNavigation = (event: React.KeyboardEvent<HTMLElement>, rowIndex: number, columnIndex: number) => {
    const key = event.key;
    if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Enter'].includes(key)) return;

    const maxRow = Math.max(0, fields.length - 1);
    const maxColumn = Math.max(0, editableColumnIds.length - 1);
    let targetRow = rowIndex;
    let targetColumn = columnIndex;

    if (key === 'ArrowLeft') targetColumn = Math.min(maxColumn, columnIndex + 1);
    if (key === 'ArrowRight') targetColumn = Math.max(0, columnIndex - 1);
    if (key === 'ArrowUp') targetRow = Math.max(0, rowIndex - 1);
    if (key === 'ArrowDown') targetRow = Math.min(maxRow, rowIndex + 1);
    if (key === 'Enter') targetRow = Math.min(maxRow, rowIndex + 1);

    const target = editableGridRef.current?.querySelector<HTMLElement>(
      `[data-grid-row="${targetRow}"][data-grid-col="${targetColumn}"]`
    );

    if (!target) return;
    event.preventDefault();
    target.focus();
    if (target instanceof HTMLInputElement) {
      target.select();
    }
  };

  const startResizeColumn = (event: React.PointerEvent<HTMLDivElement>, columnId: InvoiceColumnId) => {
    event.preventDefault();
    event.stopPropagation();

    const startX = event.clientX;
    const currentWidth = columnWidths[columnId] || columnDefById.get(columnId)?.defaultWidth || 120;
    const minWidth = columnDefById.get(columnId)?.minWidth || 80;

    const handleMove = (moveEvent: PointerEvent) => {
      const delta = moveEvent.clientX - startX;
      const nextWidth = Math.max(minWidth, currentWidth + delta);
      setColumnWidths((prev) => ({ ...prev, [columnId]: nextWidth }));
    };

    const handleUp = () => {
      document.body.style.userSelect = '';
      window.removeEventListener('pointermove', handleMove);
      window.removeEventListener('pointerup', handleUp);
    };

    document.body.style.userSelect = 'none';
    window.addEventListener('pointermove', handleMove);
    window.addEventListener('pointerup', handleUp);
  };

  const onDragColumnStart = (event: React.DragEvent<HTMLTableCellElement>, columnId: InvoiceColumnId) => {
    event.dataTransfer.setData('text/plain', columnId);
    event.dataTransfer.effectAllowed = 'move';
  };

  const onDropColumn = (event: React.DragEvent<HTMLTableCellElement>, targetColumnId: InvoiceColumnId) => {
    event.preventDefault();
    const sourceColumnId = event.dataTransfer.getData('text/plain') as InvoiceColumnId;
    if (!sourceColumnId || sourceColumnId === targetColumnId) return;

    const sourceDef = columnDefById.get(sourceColumnId);
    const targetDef = columnDefById.get(targetColumnId);
    if (!sourceDef || sourceDef.canMove === false || !targetDef) return;

    setColumnOrder((prev) => {
      const next = [...prev];
      const from = next.indexOf(sourceColumnId);
      const to = next.indexOf(targetColumnId);
      if (from === -1 || to === -1) return prev;
      next.splice(from, 1);
      next.splice(to, 0, sourceColumnId);
      return next;
    });
  };

  const resetColumnLayout = () => {
    const defaultOrder = allColumnDefs.map((column) => column.id);
    const defaultVisibility = Object.fromEntries(allColumnDefs.map((column) => [column.id, true]));
    const defaultWidths = Object.fromEntries(allColumnDefs.map((column) => [column.id, column.defaultWidth]));
    setColumnOrder(defaultOrder);
    setColumnVisibility(defaultVisibility);
    setColumnWidths(defaultWidths);
  };

  useEffect(() => {
    if (!isFullscreen) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [isFullscreen]);
  
  const parties = useMemo<Party[]>(() => {
    const customerParties: Party[] = customerList.map(c => ({
      id: `customer:${c.id}`,
      name: c.name,
      type: 'customer' as const,
      originalId: c.id
    }));
    const supplierParties: Party[] = supplierList.map(s => ({
      id: `supplier:${s.id}`,
      name: s.name,
      type: 'supplier' as const,
      originalId: s.id
    }));
    return [...customerParties, ...supplierParties];
  }, [customerList, supplierList]);
  const selectedParty = useMemo(() => parties.find(p => p.id === selectedPartyId), [parties, selectedPartyId]);
  
  const selectedCustomer = useMemo(() => {
    if (!selectedParty || selectedParty.type !== 'customer') return undefined;
    return customerList.find(c => c.id === selectedParty.originalId);
  }, [selectedParty, customerList]);

  const customerPricing = useMemo(() => {
    const category = selectedCustomer?.category || 'general';
    return allCustomerPricing.find(p => p.category === category);
  }, [selectedCustomer, allCustomerPricing]);

  const normalizeSearchText = (value: string) => {
    return value
      .toLowerCase()
      .replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, '')
      .replace(/[إأآٱ]/g, 'ا')
      .replace(/ى/g, 'ي')
      .replace(/ؤ/g, 'و')
      .replace(/ئ/g, 'ي')
      .replace(/ة/g, 'ه')
      .replace(/[^\p{L}\p{N}]+/gu, '');
  };

  const matchesMaterialSearch = (material: ProductionItem, query: string) => {
    const trimmed = query.trim();
    if (!trimmed) return true;

    const tokens = trimmed
      .split(/\s+/)
      .map((part) => normalizeSearchText(part))
      .filter(Boolean);

    if (tokens.length === 0) return true;

    const normalizedName = normalizeSearchText(material.name || '');
    const normalizedNumber = normalizeSearchText(String(material.itemNumber || material.id || ''));
    const normalizedBarcode = normalizeSearchText(material.barcode || '');
    const normalizedExtra = (material.additionalBarcodes || [])
      .map((code) => normalizeSearchText(code || ''))
      .join(' ');
    const normalizedAdditionalDetails = normalizeSearchText(material.additionalDetails || '');

    return tokens.every((token) =>
      normalizedName.includes(token) ||
      normalizedNumber.includes(token) ||
      normalizedBarcode.includes(token) ||
      normalizedExtra.includes(token) ||
      normalizedAdditionalDetails.includes(token)
    );
  };


  useEffect(() => {
    if (selectedParty && selectedParty.type === 'customer') {
      form.setValue('customerId', selectedParty.originalId);
    }
  }, [selectedParty, form]);

  useEffect(() => {
    setInvoiceDateLabel(format(new Date(), 'PPP'));
  }, []);

  // Use useWatch instead of form.watch for nested fields
  const watchAllItems = useWatch({
    control: form.control,
    name: 'items',
  });

  const watchedDiscountAmount = useWatch({
    control: form.control,
    name: 'discountAmount',
  });

  const allMaterials = useMemo(() => {
    const merged: ProductionItem[] = [];
    const seen = new Set<string>();
    for (const item of materials) {
      if (!item?.id || seen.has(item.id)) continue;
      merged.push(item);
      seen.add(item.id);
    }
    for (const item of extraMaterials) {
      if (!item?.id || seen.has(item.id)) continue;
      merged.push(item);
      seen.add(item.id);
    }
    return merged;
  }, [extraMaterials, materials]);

  const filteredMaterials = useMemo(
    () => allMaterials.filter((material) => matchesMaterialSearch(material, itemSelectQuery)),
    [allMaterials, itemSelectQuery]
  );

  const filteredPickerMaterials = useMemo(
    () => allMaterials.filter((material) => matchesMaterialSearch(material, itemPickerQuery)),
    [allMaterials, itemPickerQuery]
  );

  const getMaterialUnitPricing = (material: ProductionItem) => {
    const priceInfo = customerPricing?.prices.find((p) => p.materialId === material.id);
    const primaryPrice = Number(priceInfo?.price ?? material.salePrice ?? 0);
    const firstSecondary = Array.isArray(material.secondaryUnits) && material.secondaryUnits.length > 0
      ? material.secondaryUnits[0]
      : undefined;
    const conversionQty = Number(firstSecondary?.quantity ?? material.secondaryUnitQuantity ?? 0);

    const explicitSecondaryPrice = firstSecondary?.price;
    const secondaryPrice = Number.isFinite(Number(explicitSecondaryPrice))
      ? Number(explicitSecondaryPrice)
      : (typeof material.secondaryUnitPrice === 'number'
          ? material.secondaryUnitPrice
          : (conversionQty > 0 ? primaryPrice / conversionQty : undefined));

    return {
      primaryPrice,
      conversionQty,
      secondaryPrice: typeof secondaryPrice === 'number' && Number.isFinite(secondaryPrice) ? secondaryPrice : undefined,
      primaryUnitLabel: material.primaryUnit || '-',
      secondaryUnitLabel: String(firstSecondary?.unit || material.secondaryUnit || material.primaryUnit || '-'),
    };
  };

  const getSecondaryVolumeOptions = (material: ProductionItem, primaryPrice: number) => {
    const fromArray = Array.isArray(material.secondaryUnits)
      ? material.secondaryUnits
          .map((entry, index) => {
            const unitLabel = String(entry?.unit || '').trim();
            if (!unitLabel) return null;
            const quantity = Number(entry?.quantity || 0);
            const explicit = Number(entry?.price);
            const computedPrice = Number.isFinite(explicit)
              ? explicit
              : (quantity > 0 ? (primaryPrice / quantity) : primaryPrice);
            return {
              key: `secondary-${index}`,
              label: unitLabel,
              price: computedPrice,
              barcode: String(entry?.barcode || '').trim(),
            };
          })
          .filter((entry): entry is { key: string; label: string; price: number; barcode: string } => !!entry)
      : [];

    if (fromArray.length > 0) return fromArray;

    const legacyLabel = String(material.secondaryUnit || '').trim();
    if (!legacyLabel) return [];
    const qty = Number(material.secondaryUnitQuantity || 0);
    const price = typeof material.secondaryUnitPrice === 'number'
      ? Number(material.secondaryUnitPrice)
      : (qty > 0 ? (primaryPrice / qty) : primaryPrice);
    return [{ key: 'legacy-secondary', label: legacyLabel, price, barcode: String(material.secondaryBarcode || '').trim() }];
  };

  const itemsWithDetails = useMemo(() => {
    return watchAllItems.map(item => {
      const material = allMaterials.find(m => m.id === item.materialId);
      if (!material) return null;

      const pricing = getMaterialUnitPricing(material);
      const primaryPrice = pricing.primaryPrice;
      const secondaryPrice = pricing.secondaryPrice;
      const isSecondary = typeof secondaryPrice === 'number' && Math.abs((item.unitPrice || 0) - secondaryPrice) < 0.0001;
      const unitLabel = isSecondary ? pricing.secondaryUnitLabel : pricing.primaryUnitLabel;
      const unitBarcode = isSecondary ? (material.secondaryBarcode || '-') : (material.barcode || '-');
      const description = (item.description || '').trim() || material.name;
      const warehouseId = isWarehouseEnabled ? (item.warehouseId || defaultWarehouseId || '') : '';
      const shelfId = isWarehouseEnabled ? (item.shelfId || defaultShelfId || '') : '';
      const allowDescriptionEdit = material.allowDescriptionEdit === true;

      let bonus = 0;
      const bonusRule = customerPricing?.bonus;
      if (bonusRule && bonusRule.materialId === item.materialId && bonusRule.buyQuantity > 0 && item.quantity > 0) {
        bonus = Math.floor(item.quantity / bonusRule.buyQuantity) * bonusRule.bonusQuantity;
      }

      const lineSubtotal = (item.quantity || 0) * (item.unitPrice || 0);
      const rawDiscount = Number(item.discount || 0);
      const lineDiscount = Math.min(Math.max(rawDiscount, 0), lineSubtotal);
      const total = lineSubtotal - lineDiscount;

      return {
        name: material.name,
        description,
        allowDescriptionEdit,
        itemNumber: material.itemNumber || material.id,
        unitLabel,
        unitBarcode,
        warehouseId,
        shelfId,
        bonus,
        lineSubtotal,
        lineDiscount,
        total,
      };
    }).filter(item => item !== null);
  }, [watchAllItems, customerPricing, allMaterials, isWarehouseEnabled, defaultWarehouseId, defaultShelfId]);

  const itemsSubTotal = useMemo(() => itemsWithDetails.reduce((sum, item) => sum + (item?.lineSubtotal ?? 0), 0), [itemsWithDetails]);
  const itemDiscountTotal = useMemo(() => itemsWithDetails.reduce((sum, item) => sum + (item?.lineDiscount ?? 0), 0), [itemsWithDetails]);
  const customerDiscount = useMemo(() => ((itemsSubTotal - itemDiscountTotal) * (selectedCustomer?.allowedDiscount || 0)) / 100, [itemsSubTotal, itemDiscountTotal, selectedCustomer]);
  const safeInvoiceDiscount = useMemo(() => {
    const base = Math.max((itemsSubTotal - itemDiscountTotal) - customerDiscount, 0);
    return Math.min(Math.max(Number(watchedDiscountAmount || 0), 0), base);
  }, [itemsSubTotal, itemDiscountTotal, customerDiscount, watchedDiscountAmount]);
  const totalAfterDiscount = useMemo(() => (itemsSubTotal - itemDiscountTotal) - customerDiscount - safeInvoiceDiscount, [itemsSubTotal, itemDiscountTotal, customerDiscount, safeInvoiceDiscount]);
  const amountPaid = useMemo(() => payments.reduce((sum, payment) => sum + Number(payment.amount || 0), 0), [payments]);
  const amountDue = totalAfterDiscount - amountPaid;

  const resolveMaterialByBarcode = (barcode: string) => {
    const normalized = barcode.trim();
    for (const material of allMaterials) {
      const primaryBarcodes = [material.barcode, ...(material.additionalBarcodes || [])].filter(Boolean);
      const isPrimary = primaryBarcodes.includes(normalized);
      const secondaryOptions = getSecondaryVolumeOptions(material, Number(material.salePrice || 0));
      const matchedSecondary = secondaryOptions.find((option) => option.barcode && option.barcode === normalized);
      const isSecondary = material.secondaryBarcode === normalized || !!matchedSecondary;
      if (!isPrimary && !isSecondary) continue;

      const pricing = getMaterialUnitPricing(material);
      const primaryPrice = pricing.primaryPrice;
      const secondaryPrice = typeof pricing.secondaryPrice === 'number' ? pricing.secondaryPrice : primaryPrice;

      return {
        material,
        unitPrice: isSecondary
          ? Number(matchedSecondary?.price ?? secondaryPrice)
          : primaryPrice,
        unitType: isSecondary ? 'secondary' : 'primary',
        matchedSecondaryKey: matchedSecondary?.key,
      } as const;
    }
    return null;
  };

  const openMeasurementDialog = (material: ProductionItem, source?: { unitType?: 'primary' | 'secondary'; matchedSecondaryKey?: string }) => {
    const pricing = getMaterialUnitPricing(material);
    const isSized = (material as any).isSized === true;
    const mode: 'weight' | 'volume' = isSized ? 'volume' : 'weight';

    setPendingWeightMaterial(material);
    setPendingWeightPrimaryPrice(pricing.primaryPrice);
    setPendingMeasurementMode(mode);
    setWeightInput('');

    if (mode === 'volume') {
      const options = getSecondaryVolumeOptions(material, pricing.primaryPrice)
        .map((option) => ({ key: option.key, label: option.label, price: option.price }));
      setPendingVolumeOptions(options);

      const preferredKey = source?.unitType === 'secondary'
        ? (source?.matchedSecondaryKey || options[0]?.key || '')
        : (options[0]?.key || '');
      setSelectedVolumeOptionKey(preferredKey);

      const selected = options.find((option) => option.key === preferredKey) || options[0];
      const selectedPrice = Number(selected?.price ?? pricing.secondaryPrice ?? pricing.primaryPrice);
      setPendingWeightUnitPrice(selectedPrice);
      setPendingWeightDescription(selected ? `${material.name} - ${selected.label}` : material.name);
    } else {
      setPendingVolumeOptions([]);
      setSelectedVolumeOptionKey('');
      setPendingWeightUnitPrice(typeof pricing.secondaryPrice === 'number' ? pricing.secondaryPrice : pricing.primaryPrice);
      setPendingWeightDescription(material.name);
    }

    setShowWeightDialog(true);
  };

  const addOrIncrementItem = (materialId: string, unitPrice: number, quantity: number, description: string, warehouseId?: string, shelfId?: string) => {
    const targetWarehouseId = isWarehouseEnabled ? (warehouseId ?? defaultWarehouseId) : '';
    const targetShelfId = isWarehouseEnabled ? (shelfId ?? defaultShelfId) : '';

    const existingItemIndex = watchAllItems.findIndex((item) => {
      const sameMaterial = item.materialId === materialId;
      const samePrice = Number(item.unitPrice) === Number(unitPrice);
      if (!isWarehouseEnabled) return sameMaterial && samePrice;
      return sameMaterial && samePrice && (item.warehouseId || '') === targetWarehouseId && (item.shelfId || '') === targetShelfId;
    });

    if (existingItemIndex >= 0) {
      const currentQuantity = form.getValues(`items.${existingItemIndex}.quantity`) || 0;
      form.setValue(`items.${existingItemIndex}.quantity`, currentQuantity + quantity);
      return { updatedQuantity: currentQuantity + quantity, index: existingItemIndex };
    }

    append({ materialId, quantity, unitPrice, description, discount: 0, warehouseId: targetWarehouseId, shelfId: targetShelfId });
    return { updatedQuantity: quantity, index: -1 };
  };

  const handleBarcodeScanned = (barcode: string) => {
    const resolved = resolveMaterialByBarcode(barcode);
    if (!resolved) {
      setAddMaterialInitialValues({ barcode });
      setShowAddMaterialDialog(true);
      return;
    }

    if (resolved.material.isWeighed || (resolved.material as any).isSized) {
      openMeasurementDialog(resolved.material, {
        unitType: resolved.unitType,
        matchedSecondaryKey: resolved.matchedSecondaryKey,
      });
      setBarcodeInput("");
      return;
    }

    // Get pricing info for this material based on customer category
    const { updatedQuantity } = addOrIncrementItem(resolved.material.id, resolved.unitPrice, 1, resolved.material.name);
    toast({ 
      title: t?.itemQuantityIncreased ?? 'تمت إضافة الكمية', 
      description: `${resolved.material.name}: ${updatedQuantity}` 
    });
    setBarcodeInput("");
  };

  const handleAddMaterialFromPicker = (material: ProductionItem) => {
    const pricing = getMaterialUnitPricing(material);
    const unitPrice = pricing.primaryPrice;

    if (material.isWeighed === true || (material as any).isSized === true) {
      openMeasurementDialog(material, { unitType: 'primary' });
      return;
    }

    const { updatedQuantity } = addOrIncrementItem(material.id, unitPrice, 1, material.name);
    toast({
      title: t?.itemAdded ?? 'تمت إضافة الصنف',
      description: `${material.name}: ${updatedQuantity}`,
    });
  };

  const handleMaterialCreated = (material: ProductionItem) => {
    setExtraMaterials((prev) => {
      if (prev.find((m) => m.id === material.id) || allMaterials.find((m) => m.id === material.id)) {
        return prev;
      }
      return [material, ...prev];
    });

    const pricing = getMaterialUnitPricing(material);
    const unitPrice = pricing.primaryPrice;

    if (material.isWeighed === true || (material as any).isSized === true) {
      openMeasurementDialog(material, { unitType: 'primary' });
    } else {
      addOrIncrementItem(material.id, unitPrice, 1, material.name);
    }

    setShowAddMaterialDialog(false);
    setAddMaterialInitialValues(undefined);
  };

  const onSubmit = (values: z.infer<typeof saleInvoiceSchema>) => {
    const normalizedCustomerId = (values.customerId || '').trim();
    const isCashCustomer = normalizedCustomerId.length === 0;
    if (isCashCustomer && Math.abs(amountDue) > 0.0001) {
      form.setError('customerId', {
        type: 'manual',
        message: t?.cashCustomerRequiresPaid ?? 'الزبون النقدي يجب أن يكون المتبقي 0.00',
      });
      toast({
        title: t?.validationError ?? 'خطأ في التحقق',
        description: t?.cashCustomerRequiresPaid ?? 'الزبون النقدي يجب أن يكون المتبقي 0.00',
        variant: 'destructive',
      });
      return;
    }

    const payload = {
      ...values,
      customerId: normalizedCustomerId,
      amountPaid,
      payments: payments
        .filter(
          (payment): payment is PaymentBreakdown & { method: 'cash' | 'visa' | 'receivables' | 'coupon' } =>
            payment.method === 'cash' || payment.method === 'visa' || payment.method === 'receivables' || payment.method === 'coupon'
        )
        .map((payment) => ({
          method: payment.method,
          amount: Number(payment.amount || 0),
          customerName: payment.customerName,
          bankAccountId: payment.bankAccountId,
          couponCode: payment.couponCode,
        })),
      discountAmount: Number(values.discountAmount || 0),
      items: (values.items || []).map((item) => ({
        ...item,
        description: (item.description || '').trim(),
        discount: Number(item.discount || 0),
      })),
    };
    startTransition(async () => {
      const result = await handleCreateSaleInvoice(payload);
      if (result.success) {
        toast({ title: t?.saveInvoiceSuccess ?? 'تم حفظ الفاتورة بنجاح.', description: '' });
        form.reset({ customerId: '', discountAmount: 0, items: [] });
        setPayments([]);
        setSelectedPartyId('');
      } else {
        toast({ title: t?.saveInvoiceError ?? 'فشل حفظ الفاتورة.', description: result.error, variant: 'destructive' });
      }
    });
  };

  const visibleColumnCount = orderedVisibleColumns.length;

  const renderColumnCell = (columnId: InvoiceColumnId, index: number) => {
    const lineDetails = itemsWithDetails[index];

    switch (columnId) {
      case 'lineNo':
        return <span className="font-mono text-xs">{index + 1}</span>;
      case 'material':
        return (
          <FormField
            control={form.control}
            name={`items.${index}.materialId`}
            render={({ field }) => (
              <FormItem>
                <Select
                  onOpenChange={(open) => {
                    if (open) {
                      setItemSelectInputResetKey((prev) => prev + 1);
                    } else {
                      setItemSelectQuery('');
                    }
                  }}
                  onValueChange={(value) => {
                    field.onChange(value);
                    const priceInfo = customerPricing?.prices.find((p) => p.materialId === value);
                    const material = allMaterials.find((m) => m.id === value);
                    form.setValue(`items.${index}.unitPrice`, priceInfo?.price ?? material?.salePrice ?? 0);
                    const currentDescription = form.getValues(`items.${index}.description`);
                    if (!currentDescription && material?.name) {
                      form.setValue(`items.${index}.description`, material.name);
                    }
                  }}
                  defaultValue={field.value}
                >
                  <FormControl>
                    <SelectTrigger
                      data-grid-row={index}
                      data-grid-col={gridColumnIndex.material ?? -1}
                      onKeyDown={(event) => handleGridNavigation(event, index, gridColumnIndex.material ?? 0)}
                      title={allMaterials.find((m) => m.id === field.value)?.name || ''}
                    >
                      <SelectValue placeholder={t?.item ?? 'الصنف'} />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <div className="p-2">
                      <Input
                        key={itemSelectInputResetKey}
                        placeholder={t?.searchItemPlaceholder ?? 'ابحث عن الصنف...'}
                        defaultValue={itemSelectQuery}
                        onBlur={(e) => setItemSelectQuery(e.currentTarget.value)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') {
                            e.preventDefault();
                            setItemSelectQuery((e.currentTarget as HTMLInputElement).value);
                            (e.currentTarget as HTMLInputElement).blur();
                          }
                        }}
                        autoFocus
                      />
                    </div>
                    {filteredMaterials.length === 0 ? (
                      <SelectItem value="__no_results__" disabled>
                        {t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.'}
                      </SelectItem>
                    ) : (
                      filteredMaterials.map((m) => (
                        <SelectItem key={m.id} value={m.id} title={m.name}>{m.name}</SelectItem>
                      ))
                    )}
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />
        );
      case 'itemNumber':
        return <span className="font-mono text-xs">{lineDetails?.itemNumber ?? '-'}</span>;
      case 'description':
        return lineDetails?.allowDescriptionEdit ? (
          <FormField
            control={form.control}
            name={`items.${index}.description`}
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    {...field}
                    data-grid-row={index}
                    data-grid-col={gridColumnIndex.description ?? -1}
                    className="min-w-[140px] text-center"
                    placeholder={t?.descriptionLabel ?? 'الوصف'}
                    onFocus={(e) => e.target.select()}
                    onKeyDown={(event) => handleGridNavigation(event, index, gridColumnIndex.description ?? 0)}
                  />
                </FormControl>
              </FormItem>
            )}
          />
        ) : (
          <span className="text-sm text-muted-foreground truncate inline-block max-w-[220px]" title={lineDetails?.description ?? lineDetails?.name ?? '-'}>
            {lineDetails?.description ?? lineDetails?.name ?? '-'}
          </span>
        );
      case 'barcode':
        return <span className="font-mono text-xs">{lineDetails?.unitBarcode ?? '-'}</span>;
      case 'unit':
        return <span>{lineDetails?.unitLabel ?? '-'}</span>;
      case 'warehouse':
        return (
          <FormField
            control={form.control}
            name={`items.${index}.warehouseId`}
            render={({ field }) => (
              <FormItem>
                <Select
                  onValueChange={(value) => {
                    field.onChange(value);
                    form.setValue(`items.${index}.shelfId`, '');
                  }}
                  value={field.value || ''}
                >
                  <FormControl>
                    <SelectTrigger
                      data-grid-row={index}
                      data-grid-col={gridColumnIndex.warehouse ?? -1}
                      onKeyDown={(event) => handleGridNavigation(event, index, gridColumnIndex.warehouse ?? 0)}
                    >
                      <SelectValue placeholder={t?.warehouseLabel ?? 'المستودع'} />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {warehouses.map((warehouse) => (
                      <SelectItem key={warehouse.id} value={warehouse.id}>{warehouse.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />
        );
      case 'shelf': {
        const selectedWarehouseId = form.watch(`items.${index}.warehouseId`);
        const shelves = shelvesByWarehouse.get(selectedWarehouseId || '') || [];
        return (
          <FormField
            control={form.control}
            name={`items.${index}.shelfId`}
            render={({ field }) => (
              <FormItem>
                <Select
                  onValueChange={field.onChange}
                  value={field.value || ''}
                  disabled={!selectedWarehouseId || shelves.length === 0}
                >
                  <FormControl>
                    <SelectTrigger
                      data-grid-row={index}
                      data-grid-col={gridColumnIndex.shelf ?? -1}
                      onKeyDown={(event) => handleGridNavigation(event, index, gridColumnIndex.shelf ?? 0)}
                    >
                      <SelectValue placeholder={t?.shelfLabel ?? 'الرف'} />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {shelves.map((shelf) => (
                      <SelectItem key={shelf.id} value={shelf.id}>{shelf.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />
        );
      }
      case 'quantity':
        return (
          <FormField
            control={form.control}
            name={`items.${index}.quantity`}
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    type="number"
                    {...field}
                    data-grid-row={index}
                    data-grid-col={gridColumnIndex.quantity ?? -1}
                    onFocus={(e) => e.target.select()}
                    onKeyDown={(event) => handleGridNavigation(event, index, gridColumnIndex.quantity ?? 0)}
                  />
                </FormControl>
              </FormItem>
            )}
          />
        );
      case 'unitPrice':
        return (
          <FormField
            control={form.control}
            name={`items.${index}.unitPrice`}
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    type="number"
                    step="0.01"
                    placeholder={t?.price ?? 'السعر'}
                    {...field}
                    data-grid-row={index}
                    data-grid-col={gridColumnIndex.unitPrice ?? -1}
                    className="font-mono"
                    onFocus={(e) => e.target.select()}
                    onKeyDown={(event) => handleGridNavigation(event, index, gridColumnIndex.unitPrice ?? 0)}
                  />
                </FormControl>
              </FormItem>
            )}
          />
        );
      case 'discount':
        return (
          <FormField
            control={form.control}
            name={`items.${index}.discount`}
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    type="number"
                    step="0.01"
                    placeholder={t?.itemDiscountLabel ?? 'خصم الصنف'}
                    {...field}
                    data-grid-row={index}
                    data-grid-col={gridColumnIndex.discount ?? -1}
                    className="font-mono"
                    onFocus={(e) => e.target.select()}
                    onKeyDown={(event) => handleGridNavigation(event, index, gridColumnIndex.discount ?? 0)}
                  />
                </FormControl>
              </FormItem>
            )}
          />
        );
      case 'bonus':
        return <span className="font-mono text-green-600">+{lineDetails?.bonus ?? 0}</span>;
      case 'total':
        return <span className="text-right font-mono block">{formatCurrency(lineDetails?.total ?? 0, currencySymbol)}</span>;
      case 'actions':
        return (
          <Button type="button" variant="ghost" size="icon" onClick={() => remove(index)}>
            <Trash2 className="h-4 w-4 text-destructive" />
          </Button>
        );
      default:
        return null;
    }
  };

  return (
    <>
      <AddCustomerDialog
        open={showAddCustomerDialog}
        onOpenChange={setShowAddCustomerDialog}
        t={t}
        salesReps={salesReps}
        onCustomerAdded={(customer) => {
          setCustomerList((prev) => [...prev, customer]);
          setSelectedPartyId(`customer:${customer.id}`);
          form.setValue('customerId', customer.id);
        }}
      />
      <Dialog
        open={showAddMaterialDialog}
        onOpenChange={(open) => {
          if (!open) {
            setAddMaterialInitialValues(undefined);
          }
          setShowAddMaterialDialog(open);
        }}
      >
        <MaterialItemDialog
          items={allMaterials}
          t={t}
          tGlobal={tGlobal}
          itemGroups={itemGroups}
          categories={categories}
          initialValues={addMaterialInitialValues}
          onFinished={() => {
            setShowAddMaterialDialog(false);
            setAddMaterialInitialValues(undefined);
          }}
          onCreated={(item) => handleMaterialCreated(item as ProductionItem)}
        />
      </Dialog>
      <Card className={`w-full ${isFullscreen ? 'fixed inset-2 z-50 overflow-auto rounded-md shadow-lg' : ''}`}>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <CardHeader>
              <div className="flex items-center justify-between gap-2">
                <CardTitle>{t?.title ?? 'فاتورة مبيعات'}</CardTitle>
                <div className="flex items-center gap-2">
                  <Popover open={columnSettingsOpen} onOpenChange={setColumnSettingsOpen}>
                    <PopoverTrigger asChild>
                      <Button type="button" variant="outline" size="sm">
                        <Settings className="me-2 h-4 w-4" />
                        {t?.columnsSettings ?? 'إعدادات الأعمدة'}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[360px]">
                      <div className="space-y-3">
                        <div className="text-sm font-medium">{t?.columnsSettingsDesc ?? 'إخفاء/إظهار الأعمدة، وإعادة الترتيب من عنوان العمود بالسحب.'}</div>
                        <div className="max-h-64 space-y-2 overflow-auto">
                          {allColumnDefs.map((column) => (
                            <div key={column.id} className="flex items-center justify-between gap-2 rounded border p-2">
                              <label className="flex items-center gap-2 text-sm">
                                <input
                                  type="checkbox"
                                  checked={columnVisibility[column.id] !== false}
                                  disabled={column.canHide === false}
                                  onChange={(event) => {
                                    const checked = event.target.checked;
                                    setColumnVisibility((prev) => ({ ...prev, [column.id]: checked }));
                                  }}
                                />
                                <span>{column.label || '...'}</span>
                              </label>
                            </div>
                          ))}
                        </div>
                        <div className="flex justify-end">
                          <Button type="button" variant="outline" size="sm" onClick={resetColumnLayout}>
                            {t?.resetColumnsLayout ?? 'إعادة ضبط التخطيط'}
                          </Button>
                        </div>
                      </div>
                    </PopoverContent>
                  </Popover>
                  <Button type="button" variant="outline" size="sm" onClick={() => setIsFullscreen((prev) => !prev)}>
                    {isFullscreen ? <Minimize2 className="me-2 h-4 w-4" /> : <Maximize2 className="me-2 h-4 w-4" />}
                    {isFullscreen ? (t?.exitFullscreenInvoice ?? 'إنهاء التكبير') : (t?.fullscreenInvoice ?? 'تكبير شاشة الفاتورة')}
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              {/* Invoice Number - Display Only */}
              <FormItem>
                <FormLabel>{t?.invoiceNumber ?? 'رقم الفاتورة'}</FormLabel>
                <Input value="جديدة" readOnly disabled placeholder="سيتم إنشاؤه تلقائياً" />
              </FormItem>
              <FormField
                control={form.control}
                name="manualDocNumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.manualDocNumber ?? 'رقم السند اليدوي'}</FormLabel>
                    <FormControl>
                      <Input {...field} placeholder={t?.manualDocNumberPlaceholder ?? 'اختياري'} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
                <FormField
                control={form.control}
                name="customerId"
                render={({ field }) => (
                  <FormItem>
                  <FormLabel>{t?.selectParty ?? 'اختر زبوناً أو مورداً...'}</FormLabel>
                  <FormControl>
                    <PartySelector
                      value={selectedPartyId}
                      open={popoverOpen}
                      onOpenChange={setPopoverOpen}
                      placeholder={t?.selectParty ?? 'اختر زبوناً أو مورداً...'}
                      searchPlaceholder={t?.searchParty ?? 'ابحث عن زبون أو مورد...'}
                      options={parties.map((party) => ({
                        id: party.id,
                        label: party.name,
                        description: `(${party.type === 'customer' ? t?.customerLabel ?? 'زبون' : t?.supplierLabel ?? 'مورد'})`,
                      }))}
                      onValueChange={(partyId) => {
                        const party = parties.find((entry) => entry.id === partyId);
                        if (!party) return;
                        if (party.type === 'customer') {
                          field.onChange(party.originalId);
                        }
                        setSelectedPartyId(party.id);
                      }}
                      footerAction={
                        <Button type="button" variant="outline" className="w-full" onClick={() => setShowAddCustomerDialog(true)}>
                          {t?.addCustomerButton ?? 'إضافة زبون جديد'}
                        </Button>
                      }
                    />
                  </FormControl>
                  <FormMessage />
                  </FormItem>
                )}
                />
              <FormItem>
                <FormLabel>{t?.invoiceDate ?? 'تاريخ الفاتورة'}</FormLabel>
                <Input value={invoiceDateLabel} readOnly disabled suppressHydrationWarning />
              </FormItem>
            </div>

            <Tabs defaultValue="items" className="space-y-4">
              <InvoiceTabsNav
                itemsLabel={t?.itemDetailsTabLabel ?? 'تفاصيل الاصناف'}
                paymentLabel={t?.paymentTabLabel ?? 'الدفع'}
                notesLabel={t?.notesLabel ?? 'ملاحظات'}
                logLabel={t?.logLabel ?? 'log'}
              />

              <TabsContent value="items" forceMount className="space-y-4 data-[state=inactive]:hidden">
                <div>
                  {/* Barcode Scanner Input - Visible and Focused */}
                  <div className="mt-4 mb-4">
                    <label className="text-sm font-medium">{t?.scanBarcode ?? 'مسح الباركود'}</label>
                    <input
                      type="text"
                      value={barcodeInput}
                      onChange={(e) => setBarcodeInput(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' && barcodeInput.trim()) {
                          e.preventDefault();
                          handleBarcodeScanned(barcodeInput.trim());
                        }
                        // If barcode input is empty, allow Enter to submit the form naturally
                      }}
                      autoFocus
                      placeholder={t?.barcodePlaceholder ?? 'امسح الباركود أو أدخله هنا...'}
                      className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm"
                    />
                  </div>

                  <div className="mt-4 rounded-md border overflow-x-auto" ref={editableGridRef}>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          {orderedVisibleColumns.map((column) => (
                            <TableHead
                              key={column.id}
                              draggable={column.canMove !== false}
                              onDragStart={(event) => onDragColumnStart(event, column.id)}
                              onDragOver={(event) => event.preventDefault()}
                              onDrop={(event) => onDropColumn(event, column.id)}
                              style={{
                                width: `${columnWidths[column.id] || column.defaultWidth}px`,
                                minWidth: `${column.minWidth || 80}px`,
                              }}
                              className={column.id === 'total' ? 'text-right' : ''}
                            >
                              <div className="relative flex items-center justify-between gap-2">
                                <span>{column.label}</span>
                                <div
                                  className="absolute inset-y-0 -end-1 w-2 cursor-col-resize"
                                  onPointerDown={(event) => startResizeColumn(event, column.id)}
                                />
                              </div>
                            </TableHead>
                          ))}
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {fields.map((field, index) => (
                          <TableRow key={field.id} className="transition-all duration-150 focus-within:scale-[1.01] focus-within:bg-muted/60">
                            {orderedVisibleColumns.map((column) => (
                              <TableCell
                                key={`${field.id}-${column.id}`}
                                style={{ width: `${columnWidths[column.id] || column.defaultWidth}px` }}
                                className={column.id === 'total' ? 'text-right' : ''}
                              >
                                {renderColumnCell(column.id, index)}
                              </TableCell>
                            ))}
                          </TableRow>
                        ))}
                        {fields.length === 0 && (
                          <TableRow>
                            <TableCell colSpan={visibleColumnCount} className="text-center text-muted-foreground h-24">
                              {t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.'}
                            </TableCell>
                          </TableRow>
                        )}
                      </TableBody>
                    </Table>
                  </div>
                  <div className="mt-4">
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setShowItemPicker(true);
                        setItemPickerQuery('');
                        setItemPickerInputResetKey((prev) => prev + 1);
                      }}
                    >
                      <PlusCircle className="me-2 h-4 w-4" />{t?.addItem ?? 'إضافة صنف'}
                    </Button>
                  </div>
                  {form.formState.errors.items?.root && <p className="text-sm font-medium text-destructive mt-2">{form.formState.errors.items.root.message}</p>}
                </div>

                <Separator />

                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                  <div></div>
                  <div className="space-y-4">
                    <div className="space-y-2 rounded-md border p-4">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">{t?.subTotal ?? 'المجموع الفرعي'}</span>
                        <span className="font-mono">{formatCurrency(itemsSubTotal, currencySymbol)}</span>
                      </div>
                      {itemDiscountTotal > 0 && (
                        <div className="flex justify-between text-green-600">
                          <span className="text-muted-foreground">{t?.itemsDiscountTotalLabel ?? 'خصم الأصناف'}</span>
                          <span className="font-mono">-{formatCurrency(itemDiscountTotal, currencySymbol)}</span>
                        </div>
                      )}
                      {customerDiscount > 0 && (
                        <div className="flex justify-between text-green-600">
                          <span className="text-muted-foreground">{t?.discount ?? 'الخصم'} ({selectedCustomer?.allowedDiscount || 0}%)</span>
                          <span className="font-mono">-{formatCurrency(customerDiscount, currencySymbol)}</span>
                        </div>
                      )}
                      {safeInvoiceDiscount > 0 && (
                        <div className="flex justify-between text-green-600">
                          <span className="text-muted-foreground">{t?.invoiceDiscountLabel ?? 'خصم الإجمالي'}</span>
                          <span className="font-mono">-{formatCurrency(safeInvoiceDiscount, currencySymbol)}</span>
                        </div>
                      )}
                      <Separator />
                      <div className="flex justify-between font-bold text-lg">
                        <span>{t?.grandTotal ?? 'المجموع الإجمالي'}</span>
                        <span className="font-mono">{formatCurrency(totalAfterDiscount, currencySymbol)}</span>
                      </div>
                    </div>
                    <FormField
                      control={form.control}
                      name="discountAmount"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.invoiceDiscountLabel ?? 'خصم الإجمالي'}</FormLabel>
                          <FormControl>
                            <Input
                              type="number"
                              step="0.01"
                              className="font-mono"
                              {...field}
                              onFocus={(e) => e.target.select()}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </div>
              </TabsContent>

              <TabsContent value="payment" forceMount className="space-y-4 data-[state=inactive]:hidden">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                  <div></div>
                  <div className="space-y-4">
                    <Button type="button" variant="outline" onClick={() => setPaymentModalOpen(true)}>
                      {t?.openPaymentMethods ?? 'اختيار طرق الدفع'}
                    </Button>

                    {payments.length > 0 && (
                      <div className="space-y-2 rounded-md border p-3">
                        {payments.map((payment, idx) => (
                          <div key={`${payment.method}-${idx}`} className="flex items-center justify-between text-sm">
                            <span>
                              {payment.method === 'cash' && (t?.PaymentMethods?.cash ?? 'نقدي')}
                              {payment.method === 'visa' && (t?.PaymentMethods?.visa ?? 'فيزا')}
                              {payment.method === 'receivables' && (t?.PaymentMethods?.receivables ?? 'ذمم')}
                              {payment.method === 'coupon' && (t?.PaymentMethods?.coupon ?? 'كوبون')}
                              {payment.couponCode ? ` - ${payment.couponCode}` : ''}
                            </span>
                            <span className="font-mono">{formatCurrency(payment.amount || 0, currencySymbol)}</span>
                          </div>
                        ))}
                      </div>
                    )}

                    <div className="space-y-2 rounded-md border p-4 bg-muted/50">
                      <div className="flex justify-between text-sm">
                        <span>{t?.amountPaidLabel ?? 'المبلغ المدفوع'}</span>
                        <span className="font-mono">{formatCurrency(amountPaid, currencySymbol)}</span>
                      </div>
                    </div>

                    <div className="space-y-2 rounded-md border p-4 bg-muted/50">
                      <div className="flex justify-between font-bold text-lg">
                        <span>{t?.amountDue ?? 'المبلغ المتبقي'}</span>
                        <span className={`font-mono ${amountDue > 0 ? 'text-red-600' : 'text-green-600'}`}>{formatCurrency(amountDue, currencySymbol)}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </TabsContent>

              <TabsContent value="notes" className="space-y-4">
                <FormField
                  control={form.control}
                  name="notes"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.notesLabel ?? 'ملاحظات'}</FormLabel>
                      <FormControl>
                        <textarea
                          {...field}
                          rows={3}
                          placeholder={t?.notesPlaceholder ?? 'أضف ملاحظات إضافية هنا...'}
                          className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </TabsContent>

              <TabsContent value="log" className="space-y-4">
                <p className="text-sm text-muted-foreground">{t?.noLogEntries ?? 'لا توجد سجلات بعد.'}</p>
              </TabsContent>
            </Tabs>

          </CardContent>
          <div className="p-6 pt-0">
             <Button type="submit" disabled={isPending}>
                {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {t?.saveInvoice ?? 'حفظ الفاتورة'}
            </Button>
          </div>
          </form>
        </Form>
      </Card>

      {/* Dialog for adding new item by barcode */}
      <Dialog open={showItemPicker} onOpenChange={setShowItemPicker}>
        <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-7xl">
          <DialogHeader>
            <DialogTitle>{t?.selectItemTitle ?? 'اختيار صنف'}</DialogTitle>
            <DialogDescription>{t?.selectItemDesc ?? 'ابحث عن الصنف ثم اضغط لإضافته للفاتورة.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <Input
              key={itemPickerInputResetKey}
              ref={itemPickerInputRef}
              placeholder={t?.searchItemPlaceholder ?? 'ابحث عن الصنف...'}
              defaultValue={itemPickerQuery}
              onBlur={(e) => setItemPickerQuery(e.currentTarget.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  setItemPickerQuery((e.currentTarget as HTMLInputElement).value);
                  (e.currentTarget as HTMLInputElement).blur();
                }
              }}
              autoFocus
            />
            <div className="flex justify-end">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => {
                  setShowItemPicker(false);
                  const name = String(itemPickerInputRef.current?.value ?? itemPickerQuery).trim();
                  setItemPickerQuery(name);
                  setAddMaterialInitialValues(name ? { name } : undefined);
                  setShowAddMaterialDialog(true);
                }}
              >
                <PlusCircle className="me-2 h-4 w-4" />{t?.addNewItemTitle ?? 'إضافة صنف جديد'}
              </Button>
            </div>
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t?.item ?? 'الصنف'}</TableHead>
                    <TableHead>{t?.itemNumberLabel ?? 'رقم الصنف'}</TableHead>
                    <TableHead>{t?.itemSymbolNameLabel ?? 'اسم رمز الصنف'}</TableHead>
                    <TableHead>{t?.barcodeLabel ?? 'الباركود'}</TableHead>
                    <TableHead className="text-right">{t?.price ?? 'السعر'}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredPickerMaterials.map((material) => {
                    const priceInfo = customerPricing?.prices.find(p => p.materialId === material.id);
                    const unitPrice = priceInfo?.price ?? material.salePrice ?? 0;
                    return (
                      <TableRow
                        key={material.id}
                        className="cursor-pointer"
                        onClick={() => {
                          handleAddMaterialFromPicker(material);
                          setShowItemPicker(false);
                          setItemPickerQuery('');
                          setItemPickerInputResetKey((prev) => prev + 1);
                          setBarcodeInput('');
                        }}
                      >
                        <TableCell className="font-medium">{material.name}</TableCell>
                        <TableCell className="font-mono text-xs">{material.itemNumber || material.id}</TableCell>
                        <TableCell className="text-xs text-muted-foreground max-w-[180px] truncate">{(material.itemSymbolName || '').trim() || '-'}</TableCell>
                        <TableCell className="font-mono text-xs">{material.barcode || '-'}</TableCell>
                        <TableCell className="text-right font-mono">{formatCurrency(unitPrice, currencySymbol)}</TableCell>
                      </TableRow>
                    );
                  })}
                  {filteredPickerMaterials.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center text-muted-foreground h-24">
                        {t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.'}
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowItemPicker(false)}>
              {t?.cancel ?? 'إلغاء'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Dialog for weighed items */}
      <Dialog open={showWeightDialog} onOpenChange={setShowWeightDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{(pendingWeightMaterial as any)?.isSized ? (t?.volumeDialogTitle ?? 'إدخال الحجم') : (t?.weightDialogTitle ?? 'قراءة الوزن')}</DialogTitle>
            <DialogDescription>
              {(pendingWeightMaterial as any)?.isSized
                ? (t?.volumeDialogDesc ?? 'أدخل حجم المنتج ليتم إضافته للفاتورة.')
                : (t?.weightDialogDesc ?? 'أدخل وزن المنتج ليتم إضافته للفاتورة.')}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">{t?.itemName ?? 'اسم الصنف'}</label>
              <Input value={pendingWeightDescription || pendingWeightMaterial?.name || ''} readOnly disabled className="bg-muted" />
            </div>
            {pendingMeasurementMode === 'volume' && pendingVolumeOptions.length > 0 && (
              <div className="space-y-2">
                <label className="text-sm font-medium">{t?.secondaryUnitLabel ?? 'الوحدة الفرعية'}</label>
                <Select
                  value={selectedVolumeOptionKey}
                  onValueChange={(value) => {
                    setSelectedVolumeOptionKey(value);
                    const selected = pendingVolumeOptions.find((option) => option.key === value);
                    if (!selected || !pendingWeightMaterial) return;
                    setPendingWeightUnitPrice(Number(selected.price || 0));
                    setPendingWeightDescription(`${pendingWeightMaterial.name} - ${selected.label}`);
                  }}
                >
                  <SelectTrigger>
                    <SelectValue placeholder={t?.secondaryUnitPlaceholder ?? 'اختر الوحدة الفرعية'} />
                  </SelectTrigger>
                  <SelectContent>
                    {pendingVolumeOptions.map((option) => (
                      <SelectItem key={option.key} value={option.key}>{option.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
            <div className="space-y-2">
              <label className="text-sm font-medium">{(pendingWeightMaterial as any)?.isSized ? (t?.volumeLabel ?? 'الحجم') : (t?.weightLabel ?? 'الوزن (كغم)')}</label>
              <Input
                type="number"
                step="0.001"
                value={weightInput}
                onChange={(e) => setWeightInput(e.target.value)}
                placeholder={(pendingWeightMaterial as any)?.isSized ? (t?.volumePlaceholder ?? 'أدخل الحجم...') : (t?.weightPlaceholder ?? 'أدخل الوزن...')}
              />
            </div>
            <div className="text-xs text-muted-foreground">
              {(t?.unitPriceLabel ?? 'سعر الوحدة')}: {formatCurrency(pendingWeightUnitPrice || 0, currencySymbol)}
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowWeightDialog(false)}>
              {t?.cancel ?? 'إلغاء'}
            </Button>
            <Button
              type="button"
              variant="secondary"
              onClick={() => {
                if (!pendingWeightMaterial) return;
                const primaryDescription = pendingMeasurementMode === 'volume'
                  ? pendingWeightMaterial.name
                  : (pendingWeightDescription || pendingWeightMaterial.name);
                const { updatedQuantity } = addOrIncrementItem(
                  pendingWeightMaterial.id,
                  pendingWeightPrimaryPrice || pendingWeightUnitPrice,
                  1,
                  primaryDescription
                );

                toast({
                  title: t?.itemAdded ?? 'تمت إضافة الصنف',
                  description: `${primaryDescription}: ${updatedQuantity}`,
                });

                setShowWeightDialog(false);
                setPendingWeightMaterial(null);
                setPendingWeightUnitPrice(0);
                setPendingWeightPrimaryPrice(0);
                setPendingWeightDescription('');
                setPendingMeasurementMode('weight');
                setPendingVolumeOptions([]);
                setSelectedVolumeOptionKey('');
                setWeightInput('');
              }}
            >
              {pendingMeasurementMode === 'volume'
                ? (t?.addPrimaryUnit ?? 'إضافة بالوحدة الرئيسية')
                : (t?.addFullPackage ?? 'إضافة كامل العبوة')}
            </Button>
            <Button
              type="button"
              onClick={() => {
                const weightValue = parseFloat(weightInput);
                if (!pendingWeightMaterial || isNaN(weightValue) || weightValue <= 0) {
                  toast({
                    title: t?.validationError ?? 'خطأ في التحقق',
                    description: (pendingWeightMaterial as any)?.isSized
                      ? (t?.volumeInvalid ?? 'الرجاء إدخال حجم صحيح.')
                      : (t?.weightInvalid ?? 'الرجاء إدخال وزن صحيح.'),
                    variant: 'destructive',
                  });
                  return;
                }

                const { updatedQuantity } = addOrIncrementItem(
                  pendingWeightMaterial.id,
                  pendingWeightUnitPrice,
                  weightValue,
                  pendingWeightDescription || pendingWeightMaterial.name
                );

                toast({
                  title: t?.itemAdded ?? 'تمت إضافة الصنف',
                  description: `${pendingWeightDescription || pendingWeightMaterial.name}: ${updatedQuantity}`,
                });

                setShowWeightDialog(false);
                setPendingWeightMaterial(null);
                setPendingWeightUnitPrice(0);
                setPendingWeightPrimaryPrice(0);
                setPendingWeightDescription('');
                setPendingMeasurementMode('weight');
                setPendingVolumeOptions([]);
                setSelectedVolumeOptionKey('');
                setWeightInput('');
              }}
            >
              {t?.addItem ?? 'إضافة الصنف'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <PaymentMethodModal
        isOpen={paymentModalOpen}
        onOpenChange={setPaymentModalOpen}
        invoiceTotal={totalAfterDiscount}
        customers={customers}
        currencySymbol={currencySymbol}
        onConfirm={(paymentBreakdown) => setPayments(paymentBreakdown)}
        translations={{
          selectPaymentMethod: t?.PaymentMethods?.selectPaymentMethod ?? 'اختر طريقة الدفع',
          paymentMethods: t?.PaymentMethods?.paymentMethods ?? 'طرق الدفع',
          cash: t?.PaymentMethods?.cash ?? 'نقدي',
          visa: t?.PaymentMethods?.visa ?? 'فيزا',
          receivables: t?.PaymentMethods?.receivables ?? 'ذمم',
          coupon: t?.PaymentMethods?.coupon ?? 'كوبون',
          couponCode: t?.PaymentMethods?.couponCode ?? 'كود الكوبون',
          totalAmount: t?.PaymentMethods?.totalAmount ?? 'إجمالي الفاتورة',
          paymentBreakdown: t?.PaymentMethods?.paymentBreakdown ?? 'تفاصيل الدفع',
          remainingBalance: t?.PaymentMethods?.remainingBalance ?? 'الرصيد المتبقي',
          addPaymentMethod: t?.PaymentMethods?.addPaymentMethod ?? 'إضافة طريقة دفع',
          confirm: t?.PaymentMethods?.confirm ?? 'تأكيد',
          cancel: t?.PaymentMethods?.cancel ?? 'إلغاء',
          amount: t?.PaymentMethods?.amount ?? 'المبلغ',
          remove: t?.PaymentMethods?.remove ?? 'حذف',
          errorExceeds: t?.PaymentMethods?.errorExceeds ?? 'إجمالي الدفع لا يمكن أن يتجاوز المبلغ الإجمالي',
          errorMinimum: t?.PaymentMethods?.errorMinimum ?? 'يجب إضافة طريقة دفع واحدة على الأقل',
        }}
      />
    </>
  );
}
