﻿/**
 * Sales Invoice Form
 * Create/edit sales invoices with real data from server
 */

'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { useForm, useFieldArray, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useRouter } from 'next/navigation';
import { useToast } from '@/hooks/use-toast';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Trash2, PlusCircle, ChevronsUpDown, ChevronDown } from 'lucide-react';

import { PartySelector } from '@/components/invoice-shared/party-selector';
import { CalculationDisplay } from '@/components/invoice-shared/calculation-display';

import {
  handleCreateSalesInvoice,
  handleUpdateSalesInvoice,
} from '@/lib/actions/sales-invoice.actions';

// ─── Schema ────────────────────────────────────────────────────────────────
const lineItemSchema = z.object({
  materialId: z.string().min(1, 'اختر مادة'),
  name: z.string().optional(),
  quantity: z.coerce.number().min(0.001, 'الكمية يجب أن تكون أكبر من صفر'),
  unitPrice: z.coerce.number().min(0),
  lineDiscountPercent: z.coerce.number().min(0).max(100).optional(),
  lineDiscountAmount: z.coerce.number().min(0).optional(),
  taxRate: z.coerce.number().min(0).max(100).optional(),
  shelfId: z.string().optional(),
  description: z.string().optional(),
});

const salesInvoiceSchema = z.object({
  customerId: z.string().min(1, 'العميل مطلوب'),
  date: z.string().min(1),
  manualDocNumber: z.string().optional(),
  salesRepId: z.string().optional(),
  warehouseId: z.string().optional(),
  currencyCode: z.string().optional(),
  exchangeRate: z.coerce.number().optional(),
  taxMethod: z.enum(['tax-inclusive', 'invoice-level', 'line-level', 'tax-exempt']).optional(),
  invoiceDiscountPercent: z.coerce.number().min(0).max(100).optional(),
  invoiceDiscountAmount: z.coerce.number().min(0).optional(),
  items: z.array(lineItemSchema).min(1, 'أضف مادة واحدة على الأقل'),
  amountReceived: z.coerce.number().min(0).optional(),
  customerNotes: z.string().optional(),
  internalNotes: z.string().optional(),
});

type SalesInvoiceFormData = z.infer<typeof salesInvoiceSchema>;
type LineItemData = z.infer<typeof lineItemSchema>;
type NumericLineField = 'quantity' | 'unitPrice' | 'lineDiscountPercent' | 'lineDiscountAmount' | 'taxRate';
type GridColumnKey = 'item' | 'quantity' | 'unitPrice' | 'discountPercent' | 'taxRate' | 'shelf' | 'total';

// ─── Prop types ─────────────────────────────────────────────────────────────
export interface MaterialOption {
  id: string;
  name: string;
  itemNumber?: string;
  itemSymbolName?: string;
  barcode?: string;
  purchasePrice?: number;
  salePrice: number;
  categoryPrices?: Record<string, number>;
  primaryUnit?: string;
  taxRate?: number;
}

export interface SalesInvoiceFormProps {
  userId: string;
  userName: string;
  mode?: 'create' | 'edit';
  invoiceId?: string;
  initialData?: Partial<SalesInvoiceFormData> & { items?: any[] };
  customers: { id: string; label: string; description?: string; allowedDiscount?: number; salesRepId?: string; category?: string }[];
  materials: MaterialOption[];
  warehouses: { id: string; name: string; shelves: { id: string; name: string }[] }[];
  stockLocationsByMaterial?: Record<string, Array<{ warehouseId: string; shelfId: string; quantity: number }>>;
  warehousesEnabled?: boolean;
  blockSalesBelowCost?: boolean;
  defaultWarehouseId?: string;
  salesReps: { id: string; name: string }[];
  salesRepsEnabled?: boolean;
  currencies: { code: string; name: string; symbol?: string; exchangeRate?: number }[];
  defaultCurrencyCode?: string;
}

// ─── Helpers ─────────────────────────────────────────────────────────────────
function emptyItem(): LineItemData {
  return { materialId: '', quantity: 1, unitPrice: 0 };
}

function calcLineNet(item: LineItemData): number {
  const gross = (item.quantity || 0) * (item.unitPrice || 0);
  const discAmt = item.lineDiscountAmount != null
    ? item.lineDiscountAmount
    : gross * ((item.lineDiscountPercent || 0) / 100);
  return Math.max(0, gross - discAmt);
}

function toEnglishDigits(value: string): string {
  const arabicIndic = '٠١٢٣٤٥٦٧٨٩';
  const easternArabicIndic = '۰۱۲۳۴۵۶۷۸۹';
  return value
    .replace(/[٠-٩]/g, (digit) => String(arabicIndic.indexOf(digit)))
    .replace(/[۰-۹]/g, (digit) => String(easternArabicIndic.indexOf(digit)));
}

function normalizeDecimalInput(value: string): string {
  const english = toEnglishDigits(value);
  const dotDecimal = english.replace(/,/g, '.');
  return dotDecimal.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
}

function formatDecimal(value: number, fractionDigits = 2): string {
  const safe = Number.isFinite(value) ? value : 0;
  return safe.toLocaleString('en-US', {
    minimumFractionDigits: fractionDigits,
    maximumFractionDigits: fractionDigits,
    useGrouping: false,
  });
}

// ─── Component ───────────────────────────────────────────────────────────────
export default function SalesInvoiceForm({
  userId,
  userName,
  mode = 'create',
  invoiceId,
  initialData,
  customers,
  materials,
  warehouses,
  stockLocationsByMaterial = {},
  warehousesEnabled = false,
  blockSalesBelowCost = false,
  defaultWarehouseId,
  salesReps,
  salesRepsEnabled = false,
  currencies,
  defaultCurrencyCode,
}: SalesInvoiceFormProps) {
  const router = useRouter();
  const { toast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [activeTab, setActiveTab] = useState('items');
  const [lineDrafts, setLineDrafts] = useState<Record<string, string>>({});
  const [lineTotalDrafts, setLineTotalDrafts] = useState<Record<number, string>>({});
  const [headerDrafts, setHeaderDrafts] = useState<Record<string, string>>({});
  const [showItemPicker, setShowItemPicker] = useState(false);
  const [showLossDialog, setShowLossDialog] = useState(false);
  const [lossWarnings, setLossWarnings] = useState<Array<{ index: number; materialName: string; cost: number; unitPrice: number; quantity: number; lossPerUnit: number; lossAmount: number }>>([]);
  const [pendingPayload, setPendingPayload] = useState<any | null>(null);
  const [itemPickerQuery, setItemPickerQuery] = useState('');
  const [pickerTargetRowIndex, setPickerTargetRowIndex] = useState<number | null>(null);
  const [isRtlLayout, setIsRtlLayout] = useState(true);
  const tablePreferencesStorageKey = 'sales-invoice-grid-preferences';
  const defaultColumnWidths = {
    item: 240,
    quantity: 96,
    unitPrice: 120,
    discountPercent: 96,
    taxRate: 96,
    shelf: 130,
    total: 120,
  };
  const minColumnWidths = {
    item: 180,
    quantity: 80,
    unitPrice: 100,
    discountPercent: 80,
    taxRate: 80,
    shelf: 110,
    total: 100,
  };
  const [columnWidths, setColumnWidths] = useState(defaultColumnWidths);
  const [resizingColumnKey, setResizingColumnKey] = useState<GridColumnKey | null>(null);
  const resizeStateRef = useRef<{ key: GridColumnKey; startX: number; startWidth: number } | null>(null);

  const form = useForm<SalesInvoiceFormData>({
    resolver: zodResolver(salesInvoiceSchema),
    defaultValues: {
      customerId: initialData?.customerId ?? '',
      date: initialData?.date ?? new Date().toISOString().split('T')[0],
      manualDocNumber: initialData?.manualDocNumber ?? '',
      salesRepId: initialData?.salesRepId ?? '',
      warehouseId: initialData?.warehouseId ?? defaultWarehouseId ?? '',
      currencyCode: initialData?.currencyCode ?? defaultCurrencyCode ?? '',
      exchangeRate: initialData?.exchangeRate ?? 1,
      taxMethod: (initialData?.taxMethod as any) ?? 'line-level',
      invoiceDiscountPercent: initialData?.invoiceDiscountPercent ?? 0,
      invoiceDiscountAmount: initialData?.invoiceDiscountAmount ?? 0,
      items: initialData?.items?.length
        ? initialData.items.map((it: any) => ({
            materialId: it.materialId ?? '',
            name: it.name ?? '',
            quantity: it.quantity ?? 1,
            unitPrice: it.unitPrice ?? 0,
            lineDiscountPercent: it.lineDiscountPercent ?? 0,
            lineDiscountAmount: it.lineDiscountAmount ?? 0,
            taxRate: it.taxRate ?? 0,
            shelfId: it.shelfId ?? '',
            description: it.description ?? '',
          }))
        : [emptyItem()],
      amountReceived: initialData?.amountReceived ?? 0,
      customerNotes: initialData?.customerNotes ?? '',
      internalNotes: initialData?.internalNotes ?? '',
    },
  });

  const { fields, append, remove, move } = useFieldArray({ control: form.control, name: 'items' });
  const [draggingRowIndex, setDraggingRowIndex] = useState<number | null>(null);
  const watchedItems = useWatch({ control: form.control, name: 'items' }) || [];
  const amountReceived = form.watch('amountReceived') ?? 0;
  const watchedWarehouseId = useWatch({ control: form.control, name: 'warehouseId' }) ?? '';
  const invoiceDiscountPercent = form.watch('invoiceDiscountPercent') ?? 0;
  const invoiceDiscountAmount = form.watch('invoiceDiscountAmount') ?? 0;

  // Totals
  const subTotal = (watchedItems || []).reduce((sum, item) => sum + calcLineNet(item), 0);
  const invDisc = invoiceDiscountAmount > 0
    ? invoiceDiscountAmount
    : subTotal * (invoiceDiscountPercent / 100);
  const afterInvDisc = Math.max(0, subTotal - invDisc);
  const taxTotal = (watchedItems || []).reduce((sum, item) => {
    return sum + calcLineNet(item) * ((item.taxRate || 0) / 100);
  }, 0);
  const grandTotal = afterInvDisc + taxTotal;
  const amountDue = grandTotal - amountReceived;

  const filteredPickerMaterials = useMemo(() => {
    const q = itemPickerQuery.trim().toLowerCase();
    if (!q) return materials;
    return materials.filter((material) => {
      const haystack = [
        material.name,
        material.itemNumber,
        material.itemSymbolName,
        material.barcode,
      ].filter(Boolean).join(' ').toLowerCase();
      return haystack.includes(q);
    });
  }, [materials, itemPickerQuery]);

  const availableShelves = useMemo(() => {
    if (!warehousesEnabled) return [] as { id: string; name: string }[];
    const warehouse = warehouses.find((wh) => wh.id === watchedWarehouseId);
    return warehouse?.shelves || [];
  }, [warehousesEnabled, warehouses, watchedWarehouseId]);

  const shelfNameById = useMemo(() => {
    const map = new Map<string, string>();
    for (const warehouse of warehouses) {
      for (const shelf of warehouse.shelves || []) {
        map.set(`${warehouse.id}||${shelf.id}`, shelf.name);
      }
    }
    return map;
  }, [warehouses]);

  const stockShelfOptionsByRow = useMemo(() => {
    const out: Record<number, Array<{ id: string; name: string; quantity: number }>> = {};
    for (let index = 0; index < watchedItems.length; index += 1) {
      const item = watchedItems[index];
      const materialId = String(item?.materialId || '').trim();
      if (!materialId || !watchedWarehouseId) {
        out[index] = [];
        continue;
      }
      const locations = stockLocationsByMaterial[materialId] || [];
      const filtered = locations
        .filter((location) => String(location.warehouseId || '').trim() === watchedWarehouseId && Number(location.quantity || 0) > 0)
        .map((location) => ({
          id: String(location.shelfId || '').trim(),
          name: shelfNameById.get(`${watchedWarehouseId}||${String(location.shelfId || '').trim()}`) || String(location.shelfId || '').trim(),
          quantity: Number(location.quantity || 0),
        }))
        .filter((entry) => entry.id);

      const dedupMap = new Map<string, { id: string; name: string; quantity: number }>();
      filtered.forEach((entry) => {
        const existing = dedupMap.get(entry.id);
        if (!existing) {
          dedupMap.set(entry.id, entry);
          return;
        }
        dedupMap.set(entry.id, { ...existing, quantity: existing.quantity + entry.quantity });
      });

      const stockOptions = Array.from(dedupMap.values());
      if (stockOptions.length > 0) {
        out[index] = stockOptions;
        continue;
      }

      // Fallback: allow selecting any shelf in the selected warehouse.
      out[index] = availableShelves.map((shelf) => ({
        id: shelf.id,
        name: shelf.name,
        quantity: 0,
      }));
    }
    return out;
  }, [watchedItems, watchedWarehouseId, stockLocationsByMaterial, shelfNameById, availableShelves]);

  const hasMultipleShelvesByRow = useMemo(() => {
    const out: Record<number, boolean> = {};
    Object.entries(stockShelfOptionsByRow).forEach(([index, options]) => {
      out[Number(index)] = options.length > 1;
    });
    return out;
  }, [stockShelfOptionsByRow]);

  const editableColumns = useMemo(() => {
    let cursor = 0;
    const map: {
      item: number;
      quantity: number;
      unitPrice: number;
      discountPercent: number;
      taxRate: number;
      shelf?: number;
      total: number;
      count: number;
    } = {
      item: cursor++,
      quantity: cursor++,
      unitPrice: cursor++,
      discountPercent: cursor++,
      taxRate: cursor++,
      total: 0,
      count: 0,
    };

    if (warehousesEnabled && warehouses.length > 0) {
      map.shelf = cursor++;
    }

    map.total = cursor++;
    map.count = cursor;
    return map;
  }, [warehousesEnabled, warehouses.length]);

  useEffect(() => {
    const dir = document.documentElement.getAttribute('dir');
    const lang = document.documentElement.lang || '';
    setIsRtlLayout(dir === 'rtl' || lang.startsWith('ar'));
  }, []);

  useEffect(() => {
    try {
      const rawPreferences = window.localStorage.getItem(tablePreferencesStorageKey);
      if (!rawPreferences) return;
      const parsed = JSON.parse(rawPreferences) as { columnWidths?: Partial<typeof columnWidths> };
      if (!parsed.columnWidths) return;
      setColumnWidths((prev) => ({
        item: Math.max(minColumnWidths.item, Number(parsed.columnWidths?.item ?? prev.item)),
        quantity: Math.max(minColumnWidths.quantity, Number(parsed.columnWidths?.quantity ?? prev.quantity)),
        unitPrice: Math.max(minColumnWidths.unitPrice, Number(parsed.columnWidths?.unitPrice ?? prev.unitPrice)),
        discountPercent: Math.max(minColumnWidths.discountPercent, Number(parsed.columnWidths?.discountPercent ?? prev.discountPercent)),
        taxRate: Math.max(minColumnWidths.taxRate, Number(parsed.columnWidths?.taxRate ?? prev.taxRate)),
        shelf: Math.max(minColumnWidths.shelf, Number(parsed.columnWidths?.shelf ?? prev.shelf)),
        total: Math.max(minColumnWidths.total, Number(parsed.columnWidths?.total ?? prev.total)),
      }));
    } catch {
      // Ignore invalid local preferences.
    }
  }, []);

  useEffect(() => {
    if (!warehousesEnabled) return;
    if (!watchedWarehouseId) {
      watchedItems.forEach((_, index) => updateItem(index, 'shelfId', ''));
      return;
    }
    watchedItems.forEach((item, index) => {
      const materialId = String(item?.materialId || '').trim();
      const shelfId = String(item?.shelfId || '');
      if (!materialId) {
        if (shelfId) updateItem(index, 'shelfId', '');
        return;
      }
      const options = stockShelfOptionsByRow[index] || [];
      const validShelfIds = new Set(options.map((shelf) => shelf.id));
      if (shelfId && !validShelfIds.has(shelfId)) {
        updateItem(index, 'shelfId', '');
      }
    });
  }, [warehousesEnabled, watchedWarehouseId, watchedItems, stockShelfOptionsByRow]);

  useEffect(() => {
    window.localStorage.setItem(
      tablePreferencesStorageKey,
      JSON.stringify({
        columnWidths,
      })
    );
  }, [columnWidths]);

  useEffect(() => {
    const handleMouseMove = (event: MouseEvent) => {
      if (!resizeStateRef.current) return;
      const { key, startX, startWidth } = resizeStateRef.current;
      const delta = event.clientX - startX;
      const minWidth = minColumnWidths[key];
      setColumnWidths((prev) => ({
        ...prev,
        [key]: Math.max(minWidth, startWidth + delta),
      }));
    };

    const stopResize = () => {
      resizeStateRef.current = null;
      setResizingColumnKey(null);
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
    };

    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('mouseup', stopResize);

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', stopResize);
    };
  }, []);

  // Helpers for updating a single field of a line item
  function updateItem<K extends keyof LineItemData>(index: number, key: K, value: LineItemData[K]) {
    form.setValue(`items.${index}.${key}` as any, value, { shouldValidate: false });
  }

  function getDraftKey(index: number, field: NumericLineField): string {
    return `${index}:${field}`;
  }

  function getLineDisplayValue(index: number, field: NumericLineField, value: number | undefined, fractionDigits = 2): string {
    const key = getDraftKey(index, field);
    const draft = lineDrafts[key];
    if (draft !== undefined) return draft;
    return formatDecimal(Number(value || 0), fractionDigits);
  }

  function setLineDraft(index: number, field: NumericLineField, raw: string) {
    const key = getDraftKey(index, field);
    const normalized = normalizeDecimalInput(raw);
    setLineDrafts((prev) => ({ ...prev, [key]: normalized }));
  }

  function commitLineNumber(
    index: number,
    field: NumericLineField,
    raw: string,
    options?: { min?: number; max?: number; fallback?: number }
  ) {
    const parsed = Number(normalizeDecimalInput(raw));
    const fallback = options?.fallback ?? 0;
    let nextValue = Number.isFinite(parsed) ? parsed : fallback;
    if (typeof options?.min === 'number') nextValue = Math.max(options.min, nextValue);
    if (typeof options?.max === 'number') nextValue = Math.min(options.max, nextValue);

    updateItem(index, field as any, nextValue as any);

    const key = getDraftKey(index, field);
    setLineDrafts((prev) => {
      if (!(key in prev)) return prev;
      const next = { ...prev };
      delete next[key];
      return next;
    });
  }

  function getLineTotalDisplayValue(index: number, computedTotal: number): string {
    const draft = lineTotalDrafts[index];
    if (draft !== undefined) return draft;
    return formatDecimal(computedTotal, 2);
  }

  function setLineTotalDraft(index: number, raw: string) {
    const normalized = normalizeDecimalInput(raw);
    setLineTotalDrafts((prev) => ({ ...prev, [index]: normalized }));
  }

  function commitLineTotal(index: number, raw: string) {
    const parsedTotal = Number(normalizeDecimalInput(raw));
    const nextTotal = Number.isFinite(parsedTotal) ? Math.max(0, parsedTotal) : 0;
    const item = watchedItems?.[index];
    if (!item) return;

    const quantity = Math.max(0.001, Number(item.quantity || 0));
    let gross = nextTotal;

    if (item.lineDiscountAmount != null && Number(item.lineDiscountAmount || 0) > 0) {
      gross = nextTotal + Number(item.lineDiscountAmount || 0);
    } else if (Number(item.lineDiscountPercent || 0) > 0) {
      const factor = 1 - Number(item.lineDiscountPercent || 0) / 100;
      gross = factor > 0 ? nextTotal / factor : nextTotal;
    }

    const unitPrice = gross / quantity;
    updateItem(index, 'unitPrice', Number.isFinite(unitPrice) ? unitPrice : 0);

    setLineTotalDrafts((prev) => {
      if (!(index in prev)) return prev;
      const next = { ...prev };
      delete next[index];
      return next;
    });
  }

  function getHeaderDisplayValue(key: string, value: number | undefined, fractionDigits = 2): string {
    const draft = headerDrafts[key];
    if (draft !== undefined) return draft;
    return formatDecimal(Number(value || 0), fractionDigits);
  }

  function setHeaderDraft(key: string, raw: string) {
    const normalized = normalizeDecimalInput(raw);
    setHeaderDrafts((prev) => ({ ...prev, [key]: normalized }));
  }

  function commitHeaderNumber(
    key: 'invoiceDiscountPercent' | 'invoiceDiscountAmount' | 'amountReceived',
    raw: string,
    options?: { min?: number; max?: number; fallback?: number }
  ) {
    const parsed = Number(normalizeDecimalInput(raw));
    const fallback = options?.fallback ?? 0;
    let next = Number.isFinite(parsed) ? parsed : fallback;
    if (typeof options?.min === 'number') next = Math.max(options.min, next);
    if (typeof options?.max === 'number') next = Math.min(options.max, next);

    form.setValue(key, next, { shouldDirty: true, shouldValidate: false });

    setHeaderDrafts((prev) => {
      if (!(key in prev)) return prev;
      const out = { ...prev };
      delete out[key];
      return out;
    });
  }

  function openPickerForRow(rowIndex: number) {
    setPickerTargetRowIndex(rowIndex);
    setItemPickerQuery('');
    setShowItemPicker(true);
  }

  function handleAddMaterialFromPicker(material: MaterialOption) {
    if (pickerTargetRowIndex === null) return;
    updateItem(pickerTargetRowIndex, 'materialId', material.id);
    updateItem(pickerTargetRowIndex, 'name', material.name);
    updateItem(pickerTargetRowIndex, 'unitPrice', material.salePrice ?? 0);
    if (material.taxRate != null) {
      updateItem(pickerTargetRowIndex, 'taxRate', material.taxRate);
    }

    if (warehousesEnabled && watchedWarehouseId) {
      const locations = stockLocationsByMaterial[material.id] || [];
      const stockShelfIds = Array.from(
        new Set(
          locations
            .filter((location) => String(location.warehouseId || '').trim() === watchedWarehouseId && Number(location.quantity || 0) > 0)
            .map((location) => String(location.shelfId || '').trim())
            .filter(Boolean)
        )
      );
      const fallbackShelfIds = availableShelves.map((shelf) => shelf.id).filter(Boolean);
      const targetShelfId = stockShelfIds[0] || fallbackShelfIds[0] || '';
      updateItem(pickerTargetRowIndex, 'shelfId', targetShelfId);
    }

    setShowItemPicker(false);
    setPickerTargetRowIndex(null);
    setItemPickerQuery('');
  }

  function startColumnResize(key: GridColumnKey) {
    return (event: React.MouseEvent<HTMLDivElement>) => {
      event.preventDefault();
      event.stopPropagation();
      setResizingColumnKey(key);
      resizeStateRef.current = {
        key,
        startX: event.clientX,
        startWidth: columnWidths[key],
      };
      document.body.style.cursor = 'col-resize';
      document.body.style.userSelect = 'none';
    };
  }

  function renderResizeHandle(key: GridColumnKey) {
    return (
      <div
        className={`absolute inset-y-0 -end-1 z-10 flex w-3 cursor-col-resize items-center justify-center bg-transparent ${resizingColumnKey === key ? 'bg-emerald-100/80' : ''}`}
        onMouseDown={startColumnResize(key)}
      >
        <span
          className={`h-full w-px bg-border/80 transition-all ${resizingColumnKey === key ? 'w-[2px] bg-emerald-500' : 'group-hover:bg-emerald-300'}`}
        />
      </div>
    );
  }

  function focusCell(rowIndex: number, colIndex: number) {
    const target = document.querySelector<HTMLElement>(`[data-cell="${rowIndex}-${colIndex}"]`);
    if (target) target.focus();
  }

  function selectAllOnFocus(event: React.FocusEvent<HTMLInputElement>) {
    requestAnimationFrame(() => {
      event.target.select();
    });
  }

  function ensureSelectOnMouseDown(event: React.MouseEvent<HTMLInputElement>) {
    const input = event.target as HTMLInputElement;
    if (document.activeElement !== input) {
      event.preventDefault();
      input.focus();
      input.select();
    }
  }

  function moveGridRow(fromIndex: number, toIndex: number) {
    if (fromIndex < 0 || fromIndex >= fields.length) return;
    const boundedTarget = Math.max(0, Math.min(toIndex, fields.length - 1));
    if (boundedTarget === fromIndex) return;
    move(fromIndex, boundedTarget);
  }

  function appendEmptyRow() {
    append(emptyItem());
  }

  function handleGridKeyDown(event: React.KeyboardEvent<HTMLElement>, rowIndex: number, colIndex: number) {
    const isMoveUpShortcut = (event.altKey || event.ctrlKey) && (event.key === '-' || event.code === 'NumpadSubtract');
    const isMoveDownShortcut = (event.altKey || event.ctrlKey) && (event.key === '+' || event.code === 'NumpadAdd' || (event.key === '=' && event.shiftKey));

    if (isMoveUpShortcut || isMoveDownShortcut) {
      event.preventDefault();
      const targetRow = isMoveUpShortcut ? rowIndex - 1 : rowIndex + 1;
      moveGridRow(rowIndex, targetRow);
      const boundedRow = Math.max(0, Math.min(targetRow, fields.length - 1));
      setTimeout(() => focusCell(boundedRow, Math.max(0, Math.min(colIndex, editableColumns.count - 1))), 0);
      return;
    }

    if (!['Enter', 'Tab', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) return;
    if (event.key === 'ArrowDown' && (event.altKey || event.metaKey)) return;

    event.preventDefault();

    let nextRow = rowIndex;
    let nextCol = colIndex;

    if (event.key === 'Tab') {
      nextCol += event.shiftKey ? -1 : 1;
    } else if (event.key === 'Enter') {
      nextCol += 1;
    } else if (event.key === 'ArrowUp') {
      nextRow -= 1;
    } else if (event.key === 'ArrowDown') {
      nextRow += 1;
    } else if (event.key === 'ArrowRight') {
      nextCol += isRtlLayout ? -1 : 1;
    } else if (event.key === 'ArrowLeft') {
      nextCol += isRtlLayout ? 1 : -1;
    }

    if (nextCol >= editableColumns.count) {
      nextCol = 0;
      nextRow += 1;
    } else if (nextCol < 0) {
      nextCol = editableColumns.count - 1;
      nextRow -= 1;
    }

    if (nextRow < 0) nextRow = 0;
    if (nextRow >= fields.length) {
      const canAppendRow = event.key === 'Enter' || event.key === 'Tab' || (!isRtlLayout && event.key === 'ArrowRight') || (isRtlLayout && event.key === 'ArrowLeft');
      if (canAppendRow && !(event.key === 'Tab' && event.shiftKey)) {
        appendEmptyRow();
        nextRow = fields.length;
        nextCol = 0;
      } else {
        nextRow = Math.max(0, fields.length - 1);
      }
    }

    setTimeout(() => focusCell(nextRow, nextCol), 0);
  }

  function handleInputKeyDown(event: React.KeyboardEvent<HTMLInputElement>, rowIndex: number, colIndex: number) {
    if (['Enter', 'Tab', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', '+', '-'].includes(event.key) || event.code === 'NumpadAdd' || event.code === 'NumpadSubtract') {
      handleGridKeyDown(event as unknown as React.KeyboardEvent<HTMLElement>, rowIndex, colIndex);
    }
  }

  async function submitPayload(payload: any) {
    if (mode === 'edit' && invoiceId) {
      const result = await handleUpdateSalesInvoice(invoiceId, payload);
      if (result.success) {
        toast({ title: 'تم الحفظ', description: 'تم تحديث الفاتورة بنجاح.' });
        router.push(`/admin/sales/view/${invoiceId}`);
      } else {
        toast({ title: 'خطأ', description: result.error, variant: 'destructive' });
      }
      return;
    }

    const result = await handleCreateSalesInvoice(payload);
    if (result.success) {
      toast({ title: 'تم الإنشاء', description: 'تم إنشاء الفاتورة بنجاح.' });
      router.push(`/admin/sales/view/${result.data?.id}`);
    } else {
      toast({ title: 'خطأ', description: result.error, variant: 'destructive' });
    }
  }

  function buildPayload(data: SalesInvoiceFormData, applyLossAsDiscount: boolean) {
    const warnings: Array<{ index: number; materialName: string; cost: number; unitPrice: number; quantity: number; lossPerUnit: number; lossAmount: number }> = [];

    const items = data.items.map((item, index) => {
      const material = materials.find((m) => m.id === item.materialId);
      const purchasePrice = Number(material?.purchasePrice || 0);
      const quantity = Math.max(0, Number(item.quantity || 0));
      const unitPrice = Math.max(0, Number(item.unitPrice || 0));

      let lineDiscountAmount = Number(item.lineDiscountAmount || 0);
      if (purchasePrice > 0 && unitPrice < purchasePrice && quantity > 0) {
        const lossPerUnit = purchasePrice - unitPrice;
        const lossAmount = lossPerUnit * quantity;
        warnings.push({
          index: index + 1,
          materialName: material?.name || item.materialId,
          cost: purchasePrice,
          unitPrice,
          quantity,
          lossPerUnit,
          lossAmount,
        });
        if (applyLossAsDiscount) {
          lineDiscountAmount += lossAmount;
        }
      }

      return {
        ...item,
        lineDiscountAmount,
        warehouseId: warehousesEnabled ? (data.warehouseId || defaultWarehouseId || '') : undefined,
        name: item.name || material?.name || item.materialId,
      };
    });

    const payload = {
      ...data,
      salesRepId: salesRepsEnabled ? (data.salesRepId || undefined) : undefined,
      userId,
      userName,
      items,
    };

    return { payload, warnings };
  }

  async function continueSaveWithLossHandling() {
    if (!pendingPayload) return;
    try {
      setIsSubmitting(true);
      setShowLossDialog(false);
      const payload = pendingPayload;
      setPendingPayload(null);
      await submitPayload(payload);
    } finally {
      setIsSubmitting(false);
    }
  }

  const onSubmit = async (data: SalesInvoiceFormData) => {
    try {
      setIsSubmitting(true);
      if (warehousesEnabled && !data.warehouseId) {
        toast({ title: 'تنبيه', description: 'يرجى اختيار المستودع على مستوى الفاتورة.', variant: 'destructive' });
        setIsSubmitting(false);
        return;
      }
      const { payload, warnings } = buildPayload(data, false);

      if (warnings.length > 0) {
        setLossWarnings(warnings);
        if (blockSalesBelowCost) {
          setPendingPayload(null);
        } else {
          const adjusted = buildPayload(data, true).payload;
          setPendingPayload(adjusted);
        }
        setShowLossDialog(true);
        return;
      }

      await submitPayload(payload);
    } catch {
      toast({ title: 'خطأ', description: 'حدث خطأ أثناء الحفظ.', variant: 'destructive' });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>
          {mode === 'create' ? 'إنشاء فاتورة مبيعات' : 'تعديل الفاتورة'}
        </CardTitle>
      </CardHeader>

      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">

            <div className="rounded-lg border bg-muted/15 p-4 space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4">
                <FormItem>
                  <FormLabel>رقم السند الآلي</FormLabel>
                  <FormControl>
                    <Input value="يُولد تلقائياً عند الحفظ" readOnly disabled />
                  </FormControl>
                </FormItem>

                <FormField
                  control={form.control}
                  name="manualDocNumber"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>رقم المستند اليدوي</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="اختياري" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="customerId"
                  render={({ field }) => (
                    <FormItem className="md:col-span-1 lg:col-span-2">
                      <FormLabel>العميل *</FormLabel>
                      <FormControl>
                        <PartySelector
                          value={field.value}
                          options={customers}
                          onValueChange={(id) => {
                            field.onChange(id);
                            const cust = customers.find((c) => c.id === id);
                            if (salesRepsEnabled && cust?.salesRepId) {
                              form.setValue('salesRepId', cust.salesRepId);
                            } else if (!salesRepsEnabled) {
                              form.setValue('salesRepId', '');
                            }
                          }}
                          placeholder="اختر العميل"
                          searchPlaceholder="ابحث عن عميل..."
                          emptyLabel="لا يوجد عملاء"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="date"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>تاريخ الفاتورة *</FormLabel>
                      <FormControl>
                        <Input type="date" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {salesRepsEnabled && salesReps.length > 0 && (
                  <FormField
                    control={form.control}
                    name="salesRepId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>مندوب المبيعات</FormLabel>
                        <Select value={field.value ?? ''} onValueChange={field.onChange}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="اختر مندوباً" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {salesReps.map((rep) => (
                              <SelectItem key={rep.id} value={rep.id}>
                                {rep.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                {warehousesEnabled && warehouses.length > 0 && (
                  <FormField
                    control={form.control}
                    name="warehouseId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>المستودع (مستوى الفاتورة)</FormLabel>
                        <Select value={field.value ?? ''} onValueChange={field.onChange} dir="rtl">
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="اختر المستودع" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {warehouses.map((wh) => (
                              <SelectItem key={wh.id} value={wh.id}>
                                {wh.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                {currencies.length > 0 && (
                  <FormField
                    control={form.control}
                    name="currencyCode"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>العملة</FormLabel>
                        <Select value={field.value ?? ''} onValueChange={(val) => {
                          field.onChange(val);
                          const cur = currencies.find((c) => c.code === val);
                          if (cur?.exchangeRate) {
                            form.setValue('exchangeRate', cur.exchangeRate);
                          }
                        }}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="اختر العملة" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {currencies.map((cur) => (
                              <SelectItem key={cur.code} value={cur.code}>
                                {cur.name} ({cur.code})
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                <FormField
                  control={form.control}
                  name="exchangeRate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>سعر الصرف</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.0001"
                          min={0}
                          {...field}
                          onChange={(e) => field.onChange(parseFloat(e.target.value) || 1)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="taxMethod"
                  render={({ field }) => (
                    <FormItem>
                      <div className="rounded-md border p-3">
                        <div className="flex flex-wrap items-center gap-x-6 gap-y-2">
                          <FormLabel className="whitespace-nowrap mb-0">طريقة الضريبة</FormLabel>
                          {[
                            { value: 'line-level', label: 'ضريبة على السطر' },
                            { value: 'invoice-level', label: 'ضريبة على الفاتورة' },
                            { value: 'tax-inclusive', label: 'شامل الضريبة' },
                            { value: 'tax-exempt', label: 'معفى من الضريبة' },
                          ].map((opt) => (
                            <div key={opt.value} className="flex items-center gap-2 whitespace-nowrap">
                              <input
                                id={`tax-method-${opt.value}`}
                        <TableRow>
                          <TableHead className="w-[58px] text-center">#</TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'item' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.item}px`, minWidth: `${columnWidths.item}px` }}>
                            المادة
                            {renderResizeHandle('item')}
                          </TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'quantity' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.quantity}px`, minWidth: `${columnWidths.quantity}px` }}>
                            الكمية
                            {renderResizeHandle('quantity')}
                          </TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'unitPrice' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.unitPrice}px`, minWidth: `${columnWidths.unitPrice}px` }}>
                            سعر الوحدة
                            {renderResizeHandle('unitPrice')}
                          </TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'discountPercent' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.discountPercent}px`, minWidth: `${columnWidths.discountPercent}px` }}>
                            خصم %
                            {renderResizeHandle('discountPercent')}
                          </TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'taxRate' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.taxRate}px`, minWidth: `${columnWidths.taxRate}px` }}>
                            ضريبة %
                            {renderResizeHandle('taxRate')}
                          </TableHead>
                          {warehousesEnabled && warehouses.length > 0 && (
                            <TableHead className={`group relative ${resizingColumnKey === 'shelf' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.shelf}px`, minWidth: `${columnWidths.shelf}px` }}>
                              الرف
                              {renderResizeHandle('shelf')}
                            </TableHead>
                          )}
                          <TableHead className={`group relative text-end ${resizingColumnKey === 'total' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.total}px`, minWidth: `${columnWidths.total}px` }}>
                            الإجمالي
                            {renderResizeHandle('total')}
                          </TableHead>
                          <TableHead className="w-[120px] text-right" />
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {fields.map((field, index) => {
                          const item = watchedItems?.[index] ?? field;
                          const lineNet = calcLineNet(item);
                          const itemCol = editableColumns.item;
                          const quantityCol = editableColumns.quantity;
                          const unitPriceCol = editableColumns.unitPrice;
                          const discountPercentCol = editableColumns.discountPercent;
                          const taxRateCol = editableColumns.taxRate;
                          const shelfCol = editableColumns.shelf;
                          const totalCol = editableColumns.total;
                          const rowShelfOptions = stockShelfOptionsByRow[index] || [];
                          const hasMultipleShelves = hasMultipleShelvesByRow[index] === true;
                          const hasMaterialSelected = Boolean(String(item?.materialId || '').trim());
                          return (
                            <TableRow
                              key={field.id}
                              className="border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted"
                              onDragOver={(event) => event.preventDefault()}
                              onDrop={(event) => {
                                event.preventDefault();
                                if (draggingRowIndex === null || draggingRowIndex === index) {
                                  setDraggingRowIndex(null);
                                  return;
                                }
                                move(draggingRowIndex, index);
                                setDraggingRowIndex(null);
                                setTimeout(() => focusCell(index, itemCol), 0);
                              }}
                            >
                              <TableCell className="text-center text-xs text-muted-foreground">
                                <div className="flex items-center justify-center gap-1">
                                  <span lang="en" dir="ltr" className="font-mono">{index + 1}</span>
                                  <button
                                    type="button"
                                    draggable
                                    title="اسحب لنقل السطر"
                                    className="inline-flex h-6 w-6 items-center justify-center rounded border border-dashed text-muted-foreground hover:bg-muted"
                                    onDragStart={() => setDraggingRowIndex(index)}
                                    onDragEnd={() => setDraggingRowIndex(null)}
                                  >
                                    <ChevronsUpDown className="h-3.5 w-3.5" />
                                  </button>
                                </div>
                              </TableCell>
                              <TableCell>
                                <button
                                  type="button"
                                  data-cell={`${index}-${itemCol}`}
                                  className={`w-full min-w-0 h-9 rounded-md border px-2.5 py-2 text-sm text-start flex items-center gap-1 focus:outline-none focus:ring-2 focus:ring-ring hover:bg-muted/50 truncate ${item.materialId ? '' : 'text-muted-foreground'}`}
                                  onClick={() => openPickerForRow(index)}
                                  onKeyDown={(event) => handleGridKeyDown(event, index, itemCol)}
                                >
                                  <span className="truncate">
                                    {item.materialId
                                      ? (materials.find((m) => m.id === item.materialId)?.name || item.materialId)
                                      : 'اختر مادة'}
                                  </span>
                                  <ChevronDown className="h-3.5 w-3.5 shrink-0 ms-auto opacity-50" />
                                </button>
                                {form.formState.errors.items?.[index]?.materialId && (
                                  <p className="text-xs text-destructive mt-1">
                                    {form.formState.errors.items[index]?.materialId?.message}
                                  </p>
                                )}
                              </TableCell>
                              <TableCell>
                                <Input
                                  type="text"
                                  className="h-9 text-sm w-full min-w-0 text-center font-mono"
                                  lang="en"
                                  dir="ltr"
                                  inputMode="decimal"
                                  data-cell={`${index}-${quantityCol}`}
                                  value={getLineDisplayValue(index, 'quantity', item.quantity, 3)}
                                  onChange={(e) => setLineDraft(index, 'quantity', e.target.value)}
                                  onBlur={(e) => commitLineNumber(index, 'quantity', e.target.value, { min: 0.001, fallback: 1 })}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event, index, quantityCol)}
                                />
                              </TableCell>
                              <TableCell>
                                <Input
                                  type="text"
                                  className="h-9 text-sm w-full min-w-0 text-center font-mono"
                                  lang="en"
                                  dir="ltr"
                                  inputMode="decimal"
                                  data-cell={`${index}-${unitPriceCol}`}
                                  value={getLineDisplayValue(index, 'unitPrice', item.unitPrice, 2)}
                                  onChange={(e) => setLineDraft(index, 'unitPrice', e.target.value)}
                                  onBlur={(e) => commitLineNumber(index, 'unitPrice', e.target.value, { min: 0, fallback: 0 })}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event, index, unitPriceCol)}
                                />
                              </TableCell>
                              <TableCell>
                                <Input
                                  type="text"
                                  className="h-9 text-sm w-full min-w-0 text-center font-mono"
                                  lang="en"
                                  dir="ltr"
                                  inputMode="decimal"
                                  data-cell={`${index}-${discountPercentCol}`}
                                  placeholder="0.00"
                                  value={getLineDisplayValue(index, 'lineDiscountPercent', item.lineDiscountPercent, 2)}
                                  onChange={(e) => setLineDraft(index, 'lineDiscountPercent', e.target.value)}
                                  onBlur={(e) => {
                                    commitLineNumber(index, 'lineDiscountPercent', e.target.value, { min: 0, max: 100, fallback: 0 });
                                    updateItem(index, 'lineDiscountAmount', 0);
                                  }}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event, index, discountPercentCol)}
                                />
                              </TableCell>
                              <TableCell>
                                <Input
                                  type="text"
                                  className="h-9 text-sm w-full min-w-0 text-center font-mono"
                                  lang="en"
                                  dir="ltr"
                                  inputMode="decimal"
                                  data-cell={`${index}-${taxRateCol}`}
                                  placeholder="0.00"
                                  value={getLineDisplayValue(index, 'taxRate', item.taxRate, 2)}
                                  onChange={(e) => setLineDraft(index, 'taxRate', e.target.value)}
                                  onBlur={(e) => commitLineNumber(index, 'taxRate', e.target.value, { min: 0, max: 100, fallback: 0 })}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event, index, taxRateCol)}
                                />
                              </TableCell>
                              {warehousesEnabled && warehouses.length > 0 && typeof shelfCol === 'number' && (
                                <TableCell>
                                  <Select
                                    dir="rtl"
                                    value={item.shelfId || ''}
                                    onValueChange={(shelfId) => updateItem(index, 'shelfId', shelfId)}
                                  >
                                    <SelectTrigger
                                      className={`h-9 text-sm ${hasMultipleShelves && !item.shelfId ? 'border-red-500 ring-red-200 focus:ring-red-300' : ''}`}
                                      data-cell={`${index}-${shelfCol}`}
                                      onKeyDown={(event) => handleGridKeyDown(event, index, shelfCol)}
                                      disabled={!hasMaterialSelected || !watchedWarehouseId || rowShelfOptions.length === 0}
                                    >
                                      <SelectValue
                                        placeholder={
                                          !hasMaterialSelected
                                            ? 'اختر الصنف أولًا'
                                            : !watchedWarehouseId
                                            ? 'اختر مستودع الفاتورة أولًا'
                                            : hasMultipleShelves && !item.shelfId
                                              ? 'متعدد'
                                              : '—'
                                        }
                                      />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {rowShelfOptions.map((shelf) => (
                                        <SelectItem key={shelf.id} value={shelf.id}>
                                          {shelf.name}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                </TableCell>
                              )}
                              <TableCell className="text-end text-sm font-medium" lang="en" dir="ltr">
                                <Input
                                  type="text"
                                  tabIndex={0}
                                  className="h-9 text-sm w-full min-w-0 text-end font-mono"
                                  value={getLineTotalDisplayValue(index, lineNet)}
                                  data-cell={`${index}-${totalCol}`}
                                  onChange={(event) => setLineTotalDraft(index, event.target.value)}
                                  onBlur={(event) => commitLineTotal(index, event.target.value)}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event, index, totalCol)}
                                />
                              </TableCell>
                              <TableCell>
                                <div className="flex items-center justify-center gap-1">
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-8 w-8"
                                    title="نقل لأعلى (-)"
                                    onClick={() => move(index, Math.max(0, index - 1))}
                                    disabled={index === 0}
                                  >
                                    <span className="text-base leading-none">-</span>
                                  </Button>
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-8 w-8"
                                    title="نقل لأسفل (+)"
                                    onClick={() => move(index, Math.min(fields.length - 1, index + 1))}
                                    disabled={index === fields.length - 1}
                                  >
                                    <span className="text-base leading-none">+</span>
                                  </Button>
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-8 w-8"
                                    onClick={() => remove(index)}
                                    disabled={fields.length === 1}
                                  >
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          );
                        })}
                      </TableBody>
                    </Table>
                  </div>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={appendEmptyRow}
                  >
                    <PlusCircle className="h-4 w-4 me-2" />
                    إضافة سطر
                  </Button>
                  {form.formState.errors.items?.root?.message && (
                    <p className="text-sm text-destructive">{form.formState.errors.items.root.message}</p>
                  )}

                  {/* Invoice-level discount */}
                  <div className="grid grid-cols-2 gap-4 pt-2 border-t">
                  <FormField
                    control={form.control}
                    name="invoiceDiscountPercent"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>خصم الفاتورة %</FormLabel>
                        <FormControl>
                          <Input
                            type="text"
                            lang="en"
                            dir="ltr"
                            inputMode="decimal"
                            className="font-mono"
                            placeholder="0.00"
                            value={getHeaderDisplayValue('invoiceDiscountPercent', field.value, 2)}
                            onChange={(e) => setHeaderDraft('invoiceDiscountPercent', e.target.value)}
                            onBlur={(e) => {
                              commitHeaderNumber('invoiceDiscountPercent', e.target.value, { min: 0, max: 100, fallback: 0 });
                              form.setValue('invoiceDiscountAmount', 0, { shouldDirty: true, shouldValidate: false });
                              setHeaderDrafts((prev) => {
                                if (!('invoiceDiscountAmount' in prev)) return prev;
                                const out = { ...prev };
                                delete out.invoiceDiscountAmount;
                                return out;
                              });
                            }}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="invoiceDiscountAmount"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>مبلغ الخصم</FormLabel>
                        <FormControl>
                          <Input
                            type="text"
                            lang="en"
                            dir="ltr"
                            inputMode="decimal"
                            className="font-mono"
                            placeholder="0.00"
                            value={getHeaderDisplayValue('invoiceDiscountAmount', field.value, 2)}
                            onChange={(e) => setHeaderDraft('invoiceDiscountAmount', e.target.value)}
                            onBlur={(e) => {
                              commitHeaderNumber('invoiceDiscountAmount', e.target.value, { min: 0, fallback: 0 });
                              form.setValue('invoiceDiscountPercent', 0, { shouldDirty: true, shouldValidate: false });
                              setHeaderDrafts((prev) => {
                                if (!('invoiceDiscountPercent' in prev)) return prev;
                                const out = { ...prev };
                                delete out.invoiceDiscountPercent;
                                return out;
                              });
                            }}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                </div>
              </TabsContent>

              {/* ── Payment Tab ── */}
              <TabsContent value="payment" className="space-y-4 mt-4">
                <FormField
                  control={form.control}
                  name="amountReceived"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>المبلغ المستلم</FormLabel>
                      <FormControl>
                        <Input
                          type="text"
                          lang="en"
                          dir="ltr"
                          inputMode="decimal"
                          className="font-mono"
                          value={getHeaderDisplayValue('amountReceived', field.value, 2)}
                          onChange={(e) => setHeaderDraft('amountReceived', e.target.value)}
                          onBlur={(e) => commitHeaderNumber('amountReceived', e.target.value, { min: 0, fallback: 0 })}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <div className="rounded-md bg-muted/50 p-4 space-y-1 text-sm">
                  <div className="flex justify-between">
                    <span>المجموع الجزئي</span>
                    <span>{subTotal.toFixed(2)}</span>
                  </div>
                  {invDisc > 0 && (
                    <div className="flex justify-between text-red-600">
                      <span>خصم الفاتورة</span>
                      <span>−{invDisc.toFixed(2)}</span>
                    </div>
                  )}
                  {taxTotal > 0 && (
                    <div className="flex justify-between">
                      <span>الضريبة</span>
                      <span>{taxTotal.toFixed(2)}</span>
                    </div>
                  )}
                  <div className="flex justify-between font-semibold border-t pt-1">
                    <span>الإجمالي</span>
                    <span>{grandTotal.toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between text-muted-foreground">
                    <span>المستلم</span>
                    <span>{(amountReceived as number).toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between font-bold text-base border-t pt-1">
                    <span>المتبقي</span>
                    <span className={amountDue > 0 ? 'text-red-600' : 'text-green-600'}>
                      {amountDue.toFixed(2)}
                    </span>
                  </div>
                </div>
              </TabsContent>

              {/* ── Notes Tab ── */}
              <TabsContent value="notes" className="space-y-4 mt-4">
                <FormField
                  control={form.control}
                  name="customerNotes"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>ملاحظات للعميل</FormLabel>
                      <FormControl>
                        <Textarea rows={3} placeholder="تظهر على الفاتورة المطبوعة" {...field} />
                      </FormControl>
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="internalNotes"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>ملاحظات داخلية</FormLabel>
                      <FormControl>
                        <Textarea rows={3} placeholder="للاستخدام الداخلي فقط" {...field} />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </TabsContent>

            </Tabs>

            {/* ── Below Tabs: Tax Method + Summary ── */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-1">
              <FormField
                control={form.control}
                name="taxMethod"
                render={({ field }) => (
                  <FormItem>
                    <div className="rounded-lg border bg-card p-4 h-full">
                      <div className="text-sm font-semibold mb-3">طريقة الضريبة</div>
                      <div className="flex flex-wrap gap-x-5 gap-y-3">
                        {[
                          { value: 'line-level', label: 'ضريبة على السطر' },
                          { value: 'invoice-level', label: 'ضريبة على الفاتورة' },
                          { value: 'tax-inclusive', label: 'شامل الضريبة' },
                          { value: 'tax-exempt', label: 'معفى من الضريبة' },
                        ].map((opt) => (
                          <div key={opt.value} className="flex items-center gap-2 whitespace-nowrap">
                            <input
                              id={`tax-method-${opt.value}`}
                              type="radio"
                              className="w-4 h-4 cursor-pointer"
                              value={opt.value}
                              checked={(field.value ?? 'line-level') === opt.value}
                              onChange={() => field.onChange(opt.value)}
                            />
                            <label htmlFor={`tax-method-${opt.value}`} className="cursor-pointer text-sm">
                              {opt.label}
                            </label>
                          </div>
                        ))}
                      </div>
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="rounded-lg border bg-card">
                <div className="px-4 pt-4 pb-2">
                  <div className="text-sm font-semibold">ملخص الفاتورة</div>
                </div>
                <div className="px-4 pb-4 space-y-2 text-sm">
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">المجموع الجزئي</span>
                    <span className="font-medium font-mono" dir="ltr">{subTotal.toFixed(2)}</span>
                  </div>
                  {invDisc > 0 && (
                    <div className="flex items-center justify-between">
                      <span className="text-muted-foreground">خصم الفاتورة</span>
                      <span className="font-medium font-mono text-red-600" dir="ltr">−{invDisc.toFixed(2)}</span>
                    </div>
                  )}
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">الضريبة</span>
                    <span className="font-medium font-mono" dir="ltr">{taxTotal.toFixed(2)}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">الإجمالي</span>
                    <span className="font-medium font-mono" dir="ltr">{grandTotal.toFixed(2)}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">المستلم</span>
                    <span className="font-medium font-mono" dir="ltr">{(amountReceived as number).toFixed(2)}</span>
                  </div>
                  <div className="border-t pt-2 flex items-center justify-between">
                    <span className="font-semibold">المتبقي</span>
                    <span className="text-base font-bold font-mono" dir="ltr">{amountDue.toFixed(2)}</span>
                  </div>
                </div>
              </div>
            </div>

            {/* ── Actions ── */}
            <div className="flex gap-4 pt-2">
              <Button type="submit" disabled={isSubmitting} className="flex-1">
                {isSubmitting
                  ? 'جاري الحفظ...'
                  : mode === 'edit'
                    ? 'حفظ التعديلات'
                    : 'إنشاء الفاتورة'}
              </Button>
              <Button type="button" variant="outline" onClick={() => router.back()}>
                إلغاء
              </Button>
            </div>
          </form>

          <Dialog
            open={showItemPicker}
            onOpenChange={(open) => {
              setShowItemPicker(open);
              if (!open) {
                setPickerTargetRowIndex(null);
                setItemPickerQuery('');
              }
            }}
          >
            <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-7xl">
              <DialogHeader>
                <DialogTitle>اختيار صنف</DialogTitle>
                <DialogDescription>ابحث عن الصنف ثم اضغط لإضافته للفاتورة.</DialogDescription>
              </DialogHeader>

              <div className="space-y-4">
                <Input
                  placeholder="ابحث عن الصنف..."
                  value={itemPickerQuery}
                  onChange={(e) => setItemPickerQuery(e.target.value)}
                  autoFocus
                />
                <div className="flex justify-end">
                  <button
                    className="inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-9 rounded-md px-3"
                    type="button"
                    onClick={() => router.push('/admin/data/materials')}
                  >
                    <PlusCircle className="h-4 w-4 me-2" />
                    إضافة صنف جديد
                  </button>
                </div>

                <div className="rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>الصنف</TableHead>
                        <TableHead>رقم الصنف</TableHead>
                        <TableHead>اسم رمز الصنف</TableHead>
                        <TableHead>الباركود</TableHead>
                        <TableHead className="text-right">السعر</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredPickerMaterials.map((material) => (
                        <TableRow
                          key={material.id}
                          className="cursor-pointer"
                          onClick={() => handleAddMaterialFromPicker(material)}
                        >
                          <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" lang="en" dir="ltr">
                            {formatDecimal(material.salePrice || 0, 2)}
                          </TableCell>
                        </TableRow>
                      ))}
                      {filteredPickerMaterials.length === 0 && (
                        <TableRow>
                          <TableCell colSpan={5} className="text-center text-muted-foreground h-24">
                            لا توجد أصناف مطابقة.
                          </TableCell>
                        </TableRow>
                      )}
                    </TableBody>
                  </Table>
                </div>
              </div>

              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setShowItemPicker(false)}>
                  إلغاء
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>

          <Dialog
            open={showLossDialog}
            onOpenChange={(open) => {
              setShowLossDialog(open);
              if (!open) {
                setPendingPayload(null);
              }
            }}
          >
            <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-3xl">
              <DialogHeader>
                <DialogTitle>تنبيه خسارة أقل من سعر الشراء</DialogTitle>
                <DialogDescription>
                  {blockSalesBelowCost
                    ? 'توجد أصناف سعر بيعها أقل من سعر الشراء. تم منع الحفظ حسب إعدادات النظام، يرجى تعديل الأسعار أو الخصومات.'
                    : 'توجد أصناف سعر بيعها أقل من سعر الشراء. عند المتابعة سيتم ترحيل فرق الخسارة إلى خصم السطر تلقائيًا.'}
                </DialogDescription>
              </DialogHeader>

              <div className="rounded-md border overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-right">#</TableHead>
                      <TableHead className="text-right">الصنف</TableHead>
                      <TableHead className="text-right">سعر الشراء</TableHead>
                      <TableHead className="text-right">سعر البيع</TableHead>
                      <TableHead className="text-right">الكمية</TableHead>
                      <TableHead className="text-right">خسارة/وحدة</TableHead>
                      <TableHead className="text-right">إجمالي الخسارة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {lossWarnings.map((warning) => (
                      <TableRow key={`${warning.index}-${warning.materialName}`}>
                        <TableCell>{warning.index}</TableCell>
                        <TableCell>{warning.materialName}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end">{formatDecimal(warning.cost, 2)}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end">{formatDecimal(warning.unitPrice, 2)}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end">{formatDecimal(warning.quantity, 3)}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end text-red-600">{formatDecimal(warning.lossPerUnit, 2)}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end text-red-600">{formatDecimal(warning.lossAmount, 2)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setShowLossDialog(false)}>
                  تعديل
                </Button>
                {!blockSalesBelowCost && (
                  <Button type="button" onClick={continueSaveWithLossHandling}>
                    استمرار والحفظ
                  </Button>
                )}
              </DialogFooter>
            </DialogContent>
          </Dialog>

        </Form>
