'use client';

import { useState, useTransition, useMemo, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { useDocumentLock } from '@/hooks/use-document-lock';
import { PlusCircle, Loader2, MoreHorizontal, Pencil, Trash2, Search } from "lucide-react";
import { type ChartOfAccount, type Customer, type CustomerCategory, type SalesRep, type Supplier } from "@/lib/types";
import { handleAddListItem, handleUpdateListItem, handleDeleteListItem } from "@/lib/actions";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { formatCurrency } from "@/lib/currency-formatter";
import EmployeeAddDialog from "@/components/admin/employee-add-dialog";
import CustomerCategoryDialog from "@/components/admin/customer-category-dialog";
import AccountCodeSelector from "@/components/admin/account-code-selector";
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';

const partyItemSchema = z.discriminatedUnion('type', [
  z.object({
    type: z.literal('customer'),
    customerNumber: z.string().min(1),
    name: z.string().min(2),
    category: z.string().min(1),
    accountCode: z.string().optional(),
    phone: z.string().optional(),
    creditLimit: z.coerce.number().min(0).optional(),
    address: z.string().optional(),
    allowedDiscount: z.coerce.number().min(0).max(100).optional(),
    salesRepId: z.string().optional(),
  }),
  z.object({
    type: z.literal('supplier'),
    supplierNumber: z.string().min(1),
    name: z.string().min(2),
    accountCode: z.string().optional(),
    phone: z.string().optional(),
    address: z.string().optional(),
    paymentTerms: z.coerce.number().min(0).optional(),
    taxNumber: z.string().optional(),
  }),
]);

type PartyFormData = z.infer<typeof partyItemSchema>;

interface UnifiedPartyManagerProps {
  customers: Customer[];
  suppliers: Supplier[];
  categories: CustomerCategory[];
  salesReps: SalesRep[];
  chartOfAccounts: ChartOfAccount[];
  t: any;
  tGlobal: any;
  currencySymbol: string;
}

type PartyItem = (Customer & { type: 'customer' }) | (Supplier & { type: 'supplier' });

export default function UnifiedPartyManager({
  customers,
  suppliers,
  categories,
  salesReps,
  chartOfAccounts,
  t,
  tGlobal,
  currencySymbol = '$',
}: UnifiedPartyManagerProps) {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const [customerItems, setCustomerItems] = useState<Customer[]>(customers);
  const [supplierItems, setSupplierItems] = useState<Supplier[]>(suppliers);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [partyType, setPartyType] = useState<'customer' | 'supplier'>('customer');
  const [editingParty, setEditingParty] = useState<PartyItem | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<PartyItem | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filteredTab, setFilteredTab] = useState<'all' | 'customer' | 'supplier'>('all');
  const [runtimeSalesReps, setRuntimeSalesReps] = useState<SalesRep[]>(salesReps);
  const [runtimeCategories, setRuntimeCategories] = useState<CustomerCategory[]>(categories);
  const [employeeDialogOpen, setEmployeeDialogOpen] = useState(false);
  const [categoryDialogOpen, setCategoryDialogOpen] = useState(false);
  const addSalesRepOptionValue = '__add_new_sales_rep__';
  const addCategoryOptionValue = '__add_new_category__';
  const { lockStatus } = useDocumentLock(editingParty?.type || '', editingParty?.id || '', { enabled: dialogOpen && !!editingParty?.id });
  const isEditLocked = dialogOpen && !!editingParty && lockStatus.isLocked;

  useEffect(() => {
    setCustomerItems(customers);
  }, [customers]);

  useEffect(() => {
    setSupplierItems(suppliers);
  }, [suppliers]);

  useEffect(() => {
    setRuntimeSalesReps(salesReps);
  }, [salesReps]);

  useEffect(() => {
    setRuntimeCategories(categories);
  }, [categories]);

  const allParties = useMemo<PartyItem[]>(() => {
    const customerParties: PartyItem[] = customerItems.map(c => ({ ...c, type: 'customer' as const }));
    const supplierParties: PartyItem[] = supplierItems.map(s => ({ ...s, type: 'supplier' as const }));
    return [...customerParties, ...supplierParties];
  }, [customerItems, supplierItems]);

  const filteredParties = useMemo(() => {
    return allParties.filter(party => {
      const matchesTab = filteredTab === 'all' || party.type === filteredTab;
      const matchesSearch = !searchTerm || 
        party.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (party.type === 'customer' && String(party.customerNumber || '').includes(searchTerm)) ||
        (party.type === 'supplier' && String(party.supplierNumber || '').includes(searchTerm));
      return matchesTab && matchesSearch;
    });
  }, [allParties, searchTerm, filteredTab]);

  const closePartyDialog = () => {
    if (typeof document !== 'undefined') {
      (document.activeElement as HTMLElement | null)?.blur();
    }
    setDialogOpen(false);
  };

  const form = useForm<PartyFormData>({
    resolver: zodResolver(partyItemSchema),
    defaultValues: {
      type: 'customer',
      customerNumber: '',
      name: '',
      category: 'general',
      accountCode: '1130',
      phone: '',
      creditLimit: 0,
      address: '',
      allowedDiscount: 0,
      salesRepId: '',
    } as any,
  });

  const getCustomerPayload = (data: PartyFormData) => ({
    customerNumber: 'customerNumber' in data ? data.customerNumber : '',
    name: data.name,
    category: 'category' in data ? data.category : 'general',
    accountCode: 'accountCode' in data ? (data.accountCode || '') : '',
    phone: 'phone' in data ? data.phone : '',
    creditLimit: 'creditLimit' in data ? data.creditLimit : 0,
    address: 'address' in data ? data.address : '',
    allowedDiscount: 'allowedDiscount' in data ? data.allowedDiscount : 0,
    salesRepId: 'salesRepId' in data ? data.salesRepId : '',
  });

  const getSupplierPayload = (data: PartyFormData) => ({
    supplierNumber: 'supplierNumber' in data ? data.supplierNumber : '',
    name: data.name,
    accountCode: 'accountCode' in data ? (data.accountCode || '') : '',
    phone: 'phone' in data ? data.phone : '',
    address: 'address' in data ? data.address : '',
    paymentTerms: 'paymentTerms' in data ? data.paymentTerms : 0,
    taxNumber: 'taxNumber' in data ? data.taxNumber : '',
  });

  const customerAccountOptions = useMemo(
    () => chartOfAccounts
      .filter((account) => account.type === 'account' && !account.inactive && String(account.code || '').startsWith('11'))
      .map((account) => ({ code: account.code, label: `${account.code} - ${account.nameAr}` })),
    [chartOfAccounts]
  );

  const supplierAccountOptions = useMemo(
    () => chartOfAccounts
      .filter((account) => {
        const code = String(account.code || '').trim();
        return account.type === 'account'
          && !account.inactive
          && code.startsWith('21');
      })
      .map((account) => ({ code: account.code, label: `${account.code} - ${account.nameAr}` })),
    [chartOfAccounts]
  );

  const applyPartyTypeDefaults = (nextType: 'customer' | 'supplier') => {
    setPartyType(nextType);
    form.setValue('type', nextType as any, { shouldDirty: true, shouldValidate: false });
    form.setValue('accountCode', nextType === 'customer' ? '1130' : '2110', { shouldDirty: true, shouldValidate: true });
  };

  useEffect(() => {
    if (dialogOpen) {
      if (editingParty?.type === 'customer') {
        const customer = editingParty as Customer & { type: 'customer' };
        form.reset({
          type: 'customer',
          customerNumber: customer.customerNumber || '',
          name: customer.name,
          category: customer.category || '',
          accountCode: customer.accountCode || '1130',
          phone: customer.phone || '',
          creditLimit: customer.creditLimit || 0,
          address: customer.address || '',
          allowedDiscount: customer.allowedDiscount || 0,
          salesRepId: customer.salesRepId || '',
        });
      } else if (editingParty?.type === 'supplier') {
        const supplier = editingParty as Supplier & { type: 'supplier' };
        form.reset({
          type: 'supplier',
          supplierNumber: supplier.supplierNumber || '',
          name: supplier.name,
          accountCode: supplier.accountCode || '2110',
          phone: supplier.phone || '',
          address: supplier.address || '',
          paymentTerms: supplier.paymentTerms || 0,
          taxNumber: supplier.taxNumber || '',
        });
      } else {
        // New party form
        if (partyType === 'customer') {
          form.reset({
            type: 'customer',
            customerNumber: `C${Math.floor(Math.random() * 100000)}`,
            name: '',
            category: 'general',
            accountCode: '1130',
            phone: '',
            creditLimit: 0,
            address: '',
            allowedDiscount: 0,
            salesRepId: '',
          });
        } else {
          form.reset({
            type: 'supplier',
            supplierNumber: `S${Math.floor(Math.random() * 100000)}`,
            name: '',
            accountCode: '2110',
            phone: '',
            address: '',
            paymentTerms: 0,
            taxNumber: '',
          });
        }
      }
    }
  }, [dialogOpen, editingParty, partyType, form]);

  const onSubmit = async (data: PartyFormData) => {
    if (isEditLocked) return;

    startTransition(async () => {
      try {
        if (editingParty) {
          const payload = editingParty.type === 'customer'
            ? getCustomerPayload(data)
            : getSupplierPayload(data);
          const result = await handleUpdateListItem(editingParty.type, editingParty.id, payload);
          if (!('error' in result) || !result.error) {
            toast({ title: t?.updateSuccess ?? 'تم التحديث بنجاح' });
            if (editingParty.type === 'customer') {
              setCustomerItems((prev) => prev.map((item) => item.id === editingParty.id ? { ...item, ...(payload as Partial<Customer>) } : item));
            } else {
              setSupplierItems((prev) => prev.map((item) => item.id === editingParty.id ? { ...item, ...(payload as Partial<Supplier>) } : item));
            }
          } else {
            toast({ title: 'خطأ', description: result.error, variant: 'destructive' });
          }
        } else {
          const payload = partyType === 'customer' ? getCustomerPayload(data) : getSupplierPayload(data);
          const result = await handleAddListItem(partyType, payload);
          if (!('error' in result) || !result.error) {
            toast({ title: t?.addSuccess ?? 'تمت الإضافة بنجاح' });
            if ('item' in result && result.item) {
              if (partyType === 'customer') {
                setCustomerItems((prev) => [{ ...(result.item as Customer) }, ...prev]);
              } else {
                setSupplierItems((prev) => [{ ...(result.item as Supplier) }, ...prev]);
              }
            }
          } else {
            toast({ title: 'خطأ', description: result.error, variant: 'destructive' });
          }
        }
        closePartyDialog();
        setEditingParty(null);
      } catch (error) {
        toast({ title: 'خطأ', description: 'حدث خطأ غير متوقع', variant: 'destructive' });
      }
    });
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    startTransition(async () => {
      try {
        const result = await handleDeleteListItem(deleteTarget.type, deleteTarget.id);
        if (!('error' in result) || !result.error) {
          toast({ title: t?.deleteSuccess ?? 'تم الحذف بنجاح' });
          if (deleteTarget.type === 'customer') {
            setCustomerItems((prev) => prev.filter((item) => item.id !== deleteTarget.id));
          } else {
            setSupplierItems((prev) => prev.filter((item) => item.id !== deleteTarget.id));
          }
        } else {
          toast({ title: 'خطأ', description: result.error, variant: 'destructive' });
        }
        setDeleteTarget(null);
      } catch (error) {
        toast({ title: 'خطأ', description: 'حدث خطأ غير متوقع', variant: 'destructive' });
      }
    });
  };

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>{t?.manageParties ?? 'إدارة العملاء و الموردين'}</CardTitle>
          <CardDescription>{t?.managePartiesDescription ?? 'إضافة وتعديل وحذف العملاء والموردين.'}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Header Actions */}
          <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder={t?.searchPlaceholder ?? 'ابحث...'}
                className="pl-8"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Button onClick={() => {
              setEditingParty(null);
              setPartyType('customer');
              setDialogOpen(true);
            }}>
              <PlusCircle className="me-2 h-4 w-4" />
              {t?.addNewItem ?? 'إضافة عنصر جديد'}
            </Button>
          </div>

          {/* Tabs */}
          <Tabs value={filteredTab} onValueChange={(value) => setFilteredTab(value as any)}>
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="all">{t?.all ?? 'الكل'} ({allParties.length})</TabsTrigger>
              <TabsTrigger value="customer">{t?.customers ?? 'عملاء'} ({customerItems.length})</TabsTrigger>
              <TabsTrigger value="supplier">{t?.suppliers ?? 'موردين'} ({supplierItems.length})</TabsTrigger>
            </TabsList>

            <TabsContent value={filteredTab as any} className="space-y-4">
              {filteredParties.length === 0 ? (
                <p className="text-center text-muted-foreground py-8">{t?.noItems ?? 'لا توجد عناصر'}</p>
              ) : (
                <div className="border rounded-lg overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>{t?.type ?? 'النوع'}</TableHead>
                        <TableHead>{t?.number ?? 'الرقم'}</TableHead>
                        <TableHead>{t?.name ?? 'الاسم'}</TableHead>
                        <TableHead>{t?.phone ?? 'الهاتف'}</TableHead>
                        <TableHead className="text-end">{t?.actions ?? 'الإجراءات'}</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredParties.map((party) => (
                        <TableRow key={`${party.type}-${party.id}`}>
                          <TableCell>
                            <span className={`px-2 py-1 rounded text-xs font-medium ${
                              party.type === 'customer' 
                                ? 'bg-blue-100 text-blue-800' 
                                : 'bg-green-100 text-green-800'
                            }`}>
                              {party.type === 'customer' ? t?.customerLabel ?? 'عميل' : t?.supplierLabel ?? 'مورد'}
                            </span>
                          </TableCell>
                          <TableCell className="font-mono">
                            {party.type === 'customer' ? (party as any).customerNumber : (party as any).supplierNumber}
                          </TableCell>
                          <TableCell>{party.name}</TableCell>
                          <TableCell>{party.phone || '-'}</TableCell>
                          <TableCell className="text-end">
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button variant="ghost" size="sm">
                                  <MoreHorizontal className="h-4 w-4" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end">
                                <DropdownMenuItem onClick={() => {
                                  setEditingParty(party);
                                  setPartyType(party.type);
                                  setDialogOpen(true);
                                }}>
                                  <Pencil className="me-2 h-4 w-4" />
                                  {t?.edit ?? 'تعديل'}
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                  onClick={() => setDeleteTarget(party)}
                                  className="text-destructive"
                                >
                                  <Trash2 className="me-2 h-4 w-4" />
                                  {t?.delete ?? 'حذف'}
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>

      {/* Dialog */}
      <Dialog
        open={dialogOpen}
        onOpenChange={(open) => {
          if (!open) {
            closePartyDialog();
            return;
          }
          setDialogOpen(true);
        }}
      >
        <DialogContent className="max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingParty ? t?.editItem ?? 'تعديل عنصر' : t?.addNewItem ?? 'إضافة عنصر جديد'}</DialogTitle>
            <DialogDescription>
              {editingParty ? t?.editDescription ?? 'عدل التفاصيل أدناه' : t?.addDescription ?? 'أدخل التفاصيل أدناه'}
            </DialogDescription>
          </DialogHeader>

          {editingParty && <DocumentLockBanner lockStatus={lockStatus} />}

          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              {/* Type selector for new items */}
              {!editingParty && (
                <FormItem>
                  <FormLabel>{t?.type ?? 'النوع'}</FormLabel>
                  <Select value={partyType} onValueChange={(value) => applyPartyTypeDefaults(value as 'customer' | 'supplier')}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="customer">{t?.customerLabel ?? 'عميل'}</SelectItem>
                      <SelectItem value="supplier">{t?.supplierLabel ?? 'مورد'}</SelectItem>
                    </SelectContent>
                  </Select>
                </FormItem>
              )}

              {/* Customer Fields */}
              {partyType === 'customer' && (
                <Tabs defaultValue="general" className="w-full">
                  <TabsList className="grid w-full grid-cols-2">
                    <TabsTrigger value="general">{'بيانات عامة'}</TabsTrigger>
                    <TabsTrigger value="accounting">{'المحاسبة'}</TabsTrigger>
                  </TabsList>

                  <TabsContent value="general" className="space-y-4 mt-4">
                    <FormField
                      control={form.control}
                      name="customerNumber"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.customerNumber ?? 'رقم العميل'}</FormLabel>
                          <FormControl>
                            <Input {...field} readOnly className="bg-muted" value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="name"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.name ?? 'الاسم'} *</FormLabel>
                          <FormControl>
                            <Input placeholder={t?.namePlaceholder ?? 'أدخل الاسم'} {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="category"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.category ?? 'التصنيف'} *</FormLabel>
                          <Select
                            value={field.value || 'general'}
                            onValueChange={(value) => {
                              if (value === addCategoryOptionValue) {
                                setCategoryDialogOpen(true);
                                return;
                              }
                              field.onChange(value);
                            }}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value={addCategoryOptionValue}>{t?.addCategoryInlineOption ?? 'إضافة تصنيف جديد'}</SelectItem>
                              {runtimeCategories.map(cat => (
                                <SelectItem key={cat.id} value={cat.id}>{cat.name}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="phone"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.phone ?? 'رقم الهاتف'}</FormLabel>
                          <FormControl>
                            <Input placeholder={t?.phonePlaceholder ?? '+966...'} {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="creditLimit"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.creditLimit ?? 'حد الائتمان'}</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" inputMode="decimal" {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="address"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.address ?? 'العنوان'}</FormLabel>
                          <FormControl>
                            <Input placeholder={t?.addressPlaceholder ?? 'أدخل العنوان'} {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="allowedDiscount"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.allowedDiscount ?? 'الخصم المسموح به (%)'}</FormLabel>
                          <FormControl>
                            <Input type="number" step="0.01" min="0" max="100" {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="salesRepId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.salesRep ?? 'مندوب المبيعات'}</FormLabel>
                          <Select value={field.value || 'none'} onValueChange={(val) => {
                            if (val === addSalesRepOptionValue) {
                              setEmployeeDialogOpen(true);
                            } else {
                              field.onChange(val === 'none' ? '' : val);
                            }
                          }}>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="none">{t?.noSalesRep ?? 'بدون مندوب'}</SelectItem>
                              <SelectItem value={addSalesRepOptionValue}>{t?.addSalesRepInlineOption ?? 'إضافة مندوب جديد'}</SelectItem>
                              {runtimeSalesReps.map(rep => (
                                <SelectItem key={rep.id} value={rep.id}>{rep.name}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </TabsContent>

                  <TabsContent value="accounting" className="space-y-4 mt-4">
                    <FormField
                      control={form.control}
                      name="accountCode"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{'حساب ذمم العميل'}</FormLabel>
                          <FormControl>
                            <AccountCodeSelector
                              value={field.value || ''}
                              options={customerAccountOptions.length > 0
                                ? customerAccountOptions
                                : chartOfAccounts.filter((account) => account.type === 'account' && !account.inactive).map((account) => ({
                                    code: account.code,
                                    label: `${account.code} - ${account.nameAr}`,
                                  }))}
                              placeholder={'1130 - العملاء'}
                              onValueChange={field.onChange}
                            />
                          </FormControl>
                          <p className="text-xs text-muted-foreground">{'حساب الذمم المستخدم عند البيع الآجل والتحصيل.'}</p>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </TabsContent>
                </Tabs>
              )}

              {/* Supplier Fields */}
              {partyType === 'supplier' && (
                <Tabs defaultValue="general" className="w-full">
                  <TabsList className="grid w-full grid-cols-2">
                    <TabsTrigger value="general">{'بيانات عامة'}</TabsTrigger>
                    <TabsTrigger value="accounting">{'المحاسبة'}</TabsTrigger>
                  </TabsList>

                  <TabsContent value="general" className="space-y-4 mt-4">
                    <FormField
                      control={form.control}
                      name="supplierNumber"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.supplierNumber ?? 'رقم المورد'}</FormLabel>
                          <FormControl>
                            <Input {...field} readOnly className="bg-muted" value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="name"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.name ?? 'الاسم'} *</FormLabel>
                          <FormControl>
                            <Input placeholder={t?.namePlaceholder ?? 'أدخل الاسم'} {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="phone"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.phone ?? 'رقم الهاتف'}</FormLabel>
                          <FormControl>
                            <Input placeholder={t?.phonePlaceholder ?? '+966...'} {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="address"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.address ?? 'العنوان'}</FormLabel>
                          <FormControl>
                            <Input placeholder={t?.addressPlaceholder ?? 'أدخل العنوان'} {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="paymentTerms"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.paymentTerms ?? 'شروط الدفع (أيام)'}</FormLabel>
                          <FormControl>
                            <Input type="number" step="1" min="0" {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="taxNumber"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.taxNumber ?? 'الرقم الضريبي'}</FormLabel>
                          <FormControl>
                            <Input placeholder={t?.taxNumberPlaceholder ?? 'أدخل الرقم الضريبي'} {...field} value={field.value ?? ''} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </TabsContent>

                  <TabsContent value="accounting" className="space-y-4 mt-4">
                    <FormField
                      control={form.control}
                      name="accountCode"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{'حساب دائنين المورد'}</FormLabel>
                          <FormControl>
                            <AccountCodeSelector
                              value={field.value || ''}
                              options={supplierAccountOptions.length > 0
                                ? supplierAccountOptions
                                : chartOfAccounts.filter((account) => account.type === 'account' && !account.inactive).map((account) => ({
                                    code: account.code,
                                    label: `${account.code} - ${account.nameAr}`,
                                  }))}
                              placeholder={'2110 - الموردين'}
                              onValueChange={field.onChange}
                            />
                          </FormControl>
                          <p className="text-xs text-muted-foreground">{'يُستخدم هذا الحساب تلقائيًا في قيود فواتير المشتريات ومدفوعات المورد.'}</p>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </TabsContent>
                </Tabs>
              )}

              <DialogFooter>
                <Button type="button" variant="outline" onClick={closePartyDialog}>
                  {t?.cancel ?? 'إلغاء'}
                </Button>
                <Button type="submit" disabled={isPending || isEditLocked}>
                  {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                  {t?.save ?? 'حفظ'}
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t?.deleteConfirm ?? 'تأكيد الحذف'}</AlertDialogTitle>
            <AlertDialogDescription>
              {t?.deleteMessage ?? `هل تريد حذف "${deleteTarget?.name}" بشكل دائم؟`}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t?.cancel ?? 'إلغاء'}</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} disabled={isPending} className="bg-destructive">
              {t?.delete ?? 'حذف'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <EmployeeAddDialog
        open={employeeDialogOpen}
        onOpenChange={setEmployeeDialogOpen}
        t={t}
        defaultBusinessRole="مندوب مبيعات"
        lockBusinessRole
        onEmployeeCreated={(employee) => {
          const createdRep: SalesRep | null = employee?.id
            ? {
                id: String(employee.id),
                name: String(employee.name || '').trim(),
                phone: String(employee.phone || '').trim(),
                region: String(employee.region || '').trim(),
                commissionRate: Number.isFinite(employee.commissionRate) ? Number(employee.commissionRate) : 0,
              }
            : null;
          if (!createdRep) return;
          setRuntimeSalesReps((prev) => {
            if (prev.some((entry) => entry.id === createdRep.id)) return prev;
            return [...prev, createdRep];
          });
          form.setValue('salesRepId', createdRep.id);
        }}
      />

      <CustomerCategoryDialog
        open={categoryDialogOpen}
        onOpenChange={setCategoryDialogOpen}
        t={{ ...tGlobal, ...t }}
        onCategoryCreated={(category) => {
          const newCategory: CustomerCategory = {
            id: String(category.id),
            name: String(category.name),
            categoryNumber: String(category.categoryNumber || '').trim() || undefined,
            nameEn: String(category.nameEn || '').trim() || undefined,
            discountPercent: Number(category.discountPercent || 0),
            description: String(category.description || '').trim() || undefined,
          };
          setRuntimeCategories((prev) => {
            if (prev.some((entry) => entry.id === newCategory.id || String(entry.name || '').trim().toLowerCase() === newCategory.name.trim().toLowerCase())) {
              return prev;
            }
            return [...prev, newCategory].sort((left, right) => String(left.name || '').localeCompare(String(right.name || '')));
          });
          form.setValue('category', newCategory.id);
        }}
      />
    </div>
  );
}
