'use client';

import { useEffect, useMemo, useTransition } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { handleAddEmployee } from '@/lib/actions';
import type { ChartOfAccount, EmployeePermissionProfile } from '@/lib/types';
import AccountCodeSelector from '@/components/admin/account-code-selector';

const addEmployeeSchema = z.object({
  name: z.string().min(2, 'يجب أن يحتوي الاسم على حرفين على الأقل.'),
  employeeCode: z.string().optional(),
  nationalId: z.string().optional(),
  workEmail: z.string().email('صيغة البريد الإلكتروني غير صحيحة.').optional().or(z.literal('')),
  birthDate: z.string().optional(),
  gender: z.enum(['male', 'female', 'other']).optional(),
  hireDate: z.string().optional(),
  department: z.string().optional(),
  managerName: z.string().optional(),
  workLocation: z.string().optional(),
  emergencyContactName: z.string().optional(),
  emergencyContactPhone: z.string().optional(),
  employeeCashAccountCode: z.string().optional(),
  payrollExpenseAccountCode: z.string().optional(),
  payrollLiabilityAccountCode: z.string().optional(),
  employeeAdvanceAccountCode: z.string().optional(),
  businessRole: z.string().min(1, 'الوظيفة مطلوبة.'),
  username: z.string().min(3, 'يجب أن يحتوي اسم المستخدم على 3 أحرف على الأقل.').refine((val) => !val.includes(' '), 'لا يمكن أن يحتوي اسم المستخدم على مسافات.'),
  password: z.string().min(6, 'يجب أن تحتوي كلمة المرور على 6 أحرف على الأقل.'),
  phone: z.string().optional(),
  region: z.string().optional(),
  commissionRate: z.coerce.number().min(0).max(100).optional(),
  salaryType: z.enum(['monthly', 'daily']),
  salary: z.coerce.number().min(0, 'يجب أن تكون قيمة الراتب رقمًا موجبًا.'),
  allowedPto: z.coerce.number().int().min(0, 'يجب أن تكون أيام الإجازة رقمًا موجبًا.'),
  status: z.enum(['permanent', 'temporary']),
  defaultShift: z.enum(['first', 'second', 'none']),
  role: z.enum(['admin', 'employee', 'pos']).optional().default('employee'),
  permissionProfileId: z.string().optional(),
  warehouseIds: z.array(z.string()).optional(),
});

const BUSINESS_ROLE_PRESETS = ['موظف', 'مندوب مبيعات', 'محاسب', 'أمين مخزن', 'مدير فرع'];

type AccountOption = { code: string; label: string };

function buildAccountOptions(
  accounts: ChartOfAccount[] | undefined,
  kind: 'payrollExpense' | 'payrollLiability' | 'employeeAdvance'
): AccountOption[] {
  const list = (accounts || []).filter((entry) => entry.type === 'account' && !entry.inactive);
  const byCode = new Map(list.map((entry) => [String(entry.code), entry]));

  const preferredCodesByKind: Record<typeof kind, string[]> = {
    payrollExpense: ['5210'],
    payrollLiability: ['2160'],
    employeeAdvance: ['1150', '1340'],
  };

  const fallbackLabelsByCode: Record<string, string> = {
    '5210': 'رواتب وأجور',
    '2160': 'رواتب مستحقة',
    '1150': 'سلف الموظفين',
    '1340': 'ذمم موظفين',
  };

  const preferredCodes = preferredCodesByKind[kind];
  const preferred = preferredCodes
    .map((code) => {
      const account = byCode.get(code);
      if (!account) return null;
      return { code, label: `${code} - ${account.nameAr}` } as AccountOption;
    })
    .filter((entry): entry is AccountOption => Boolean(entry));

  const keywordFiltered = list.filter((account) => {
    const code = String(account.code || '');
    const nameAr = String(account.nameAr || '').toLowerCase();

    if (kind === 'payrollExpense') {
      return account.nature === 'debit' && (
        code.startsWith('52') ||
        nameAr.includes('رواتب') ||
        nameAr.includes('أجور')
      );
    }

    if (kind === 'payrollLiability') {
      return account.nature === 'credit' && (
        code.startsWith('21') ||
        nameAr.includes('رواتب') ||
        nameAr.includes('مستحقة')
      );
    }

    return account.nature === 'debit' && (
      code.startsWith('11') ||
      code.startsWith('13') ||
      nameAr.includes('سلف') ||
      nameAr.includes('ذمم موظفين') ||
      nameAr.includes('موظف')
    );
  });

  const dynamic = keywordFiltered
    .sort((a, b) => String(a.code).localeCompare(String(b.code)))
    .map((account) => ({ code: String(account.code), label: `${account.code} - ${account.nameAr}` }));

  const merged = [...preferred, ...dynamic.filter((entry) => !preferred.some((p) => p.code === entry.code))];
  if (merged.length > 0) return merged;

  return preferredCodes.map((code) => ({ code, label: `${code} - ${fallbackLabelsByCode[code] || 'حساب'}` }));
}

function isSalesBusinessRole(value?: string) {
  const normalized = String(value || '').trim().toLowerCase();
  return normalized === 'مندوب مبيعات' || normalized === 'sales rep' || normalized === 'sales-rep';
}

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  t: any;
  warehouses?: any[];
  chartAccounts?: ChartOfAccount[];
  permissionProfiles?: EmployeePermissionProfile[];
  defaultBusinessRole?: string;
  lockBusinessRole?: boolean;
  onEmployeeCreated?: (employee: any) => void;
};

function getDefaultProfileId(permissionProfiles: EmployeePermissionProfile[], role: 'admin' | 'employee' | 'pos') {
  return permissionProfiles.find((profile) => profile.role === role)?.id || '';
}

export default function EmployeeAddDialog({
  open,
  onOpenChange,
  t,
  warehouses = [],
  chartAccounts = [],
  permissionProfiles = [],
  defaultBusinessRole = 'موظف',
  lockBusinessRole = false,
  onEmployeeCreated,
}: Props) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();

  const form = useForm<z.infer<typeof addEmployeeSchema>>({
    resolver: zodResolver(addEmployeeSchema),
    defaultValues: {
      name: '',
      employeeCode: '',
      nationalId: '',
      workEmail: '',
      birthDate: '',
      gender: undefined,
      hireDate: '',
      department: '',
      managerName: '',
      workLocation: '',
      emergencyContactName: '',
      emergencyContactPhone: '',
      employeeCashAccountCode: '',
      payrollExpenseAccountCode: '5210',
      payrollLiabilityAccountCode: '2160',
      employeeAdvanceAccountCode: '1150',
      businessRole: defaultBusinessRole,
      username: '',
      password: '',
      phone: '',
      region: '',
      commissionRate: undefined,
      salaryType: 'monthly',
      salary: 0,
      allowedPto: 15,
      status: 'permanent',
      defaultShift: 'none',
      role: 'employee',
      permissionProfileId: getDefaultProfileId(permissionProfiles, 'employee'),
      warehouseIds: [],
    },
  });

  const watchStatus = form.watch('status');
  const watchBusinessRole = form.watch('businessRole');
  const watchRole = form.watch('role') || 'employee';
  const watchWorkLocation = form.watch('workLocation');
  const payrollExpenseOptions = buildAccountOptions(chartAccounts, 'payrollExpense');
  const payrollLiabilityOptions = buildAccountOptions(chartAccounts, 'payrollLiability');
  const employeeAdvanceOptions = buildAccountOptions(chartAccounts, 'employeeAdvance');
  const warehouseLocationOptions = useMemo(
    () => (warehouses || []).map((wh: any) => {
      const name = String(wh?.name || '').trim();
      const branchName = String(wh?.branchName || '').trim();
      const location = String(wh?.location || '').trim();
      const reference = String(wh?.warehouseNumber || '').trim();
      const label = [branchName, name, location].filter(Boolean).join(' - ') || name || '-';
      const details = reference ? `${reference} - ${label}` : label;
      const departments = Array.isArray(wh?.departments)
        ? wh.departments.map((entry: any) => String(entry || '').trim()).filter(Boolean)
        : [];
      return { value: label, label: details, departments };
    }),
    [warehouses],
  );

  const availableDepartments = useMemo(() => {
    const currentLocation = String(watchWorkLocation || '').trim();
    if (!currentLocation) {
      const merged = warehouseLocationOptions.flatMap((entry) => entry.departments || []);
      return Array.from(new Set(merged));
    }
    const matched = warehouseLocationOptions.find((entry) => entry.value === currentLocation);
    return matched?.departments || [];
  }, [warehouseLocationOptions, watchWorkLocation]);

  useEffect(() => {
    const currentDepartment = String(form.getValues('department') || '').trim();
    if (!currentDepartment) return;
    if (!availableDepartments.includes(currentDepartment)) {
      form.setValue('department', '');
    }
  }, [availableDepartments, form]);

  useEffect(() => {
    if (open) {
      form.reset({
        name: '',
        employeeCode: '',
        nationalId: '',
        workEmail: '',
        birthDate: '',
        gender: undefined,
        hireDate: '',
        department: '',
        managerName: '',
        workLocation: '',
        emergencyContactName: '',
        emergencyContactPhone: '',
        employeeCashAccountCode: '',
        payrollExpenseAccountCode: '5210',
        payrollLiabilityAccountCode: '2160',
        employeeAdvanceAccountCode: '1150',
        businessRole: defaultBusinessRole,
        username: '',
        password: '',
        phone: '',
        region: '',
        commissionRate: undefined,
        salaryType: 'monthly',
        salary: 0,
        allowedPto: 15,
        status: 'permanent',
        defaultShift: 'none',
        role: 'employee',
        permissionProfileId: getDefaultProfileId(permissionProfiles, 'employee'),
        warehouseIds: [],
      });
    }
  }, [open, form, defaultBusinessRole, permissionProfiles]);

  useEffect(() => {
    const selectedProfileId = String(form.getValues('permissionProfileId') || '').trim();
    const selectedProfile = permissionProfiles.find((profile) => profile.id === selectedProfileId);
    if (selectedProfile?.role === watchRole) return;

    form.setValue('permissionProfileId', getDefaultProfileId(permissionProfiles, watchRole), {
      shouldDirty: selectedProfileId.length > 0,
      shouldValidate: false,
    });
  }, [form, permissionProfiles, watchRole]);

  useEffect(() => {
    if (watchStatus === 'temporary') {
      form.setValue('salary', 0);
      form.setValue('salaryType', 'daily');
    }
  }, [watchStatus, form]);

  useEffect(() => {
    if (lockBusinessRole) {
      form.setValue('businessRole', defaultBusinessRole);
    }
  }, [lockBusinessRole, defaultBusinessRole, form]);

  const onSubmit = (values: z.infer<typeof addEmployeeSchema>) => {
    startTransition(async () => {
      const result = await handleAddEmployee(values);
      if (result.success) {
        toast({
          title: t?.saveSuccessTitle || 'تم الحفظ',
          description: t?.addEmployeeSuccess || 'تمت إضافة الموظف بنجاح.',
        });
        onEmployeeCreated?.((result as any).employee);
        onOpenChange(false);
      } else {
        toast({
          title: t?.saveErrorTitle || 'خطأ',
          description: result.error || t?.addEmployeeFailed || 'تعذر إضافة الموظف.',
          variant: 'destructive',
        });
      }
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{t?.addDialogTitle || 'إضافة موظف جديد'}</DialogTitle>
          <DialogDescription>{t?.addDialogDescription || 'أدخل بيانات الموظف أدناه.'}</DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <Tabs defaultValue="basic" className="w-full">
              <TabsList className="grid w-full grid-cols-3">
                <TabsTrigger value="basic">{t?.basicTab || 'البيانات الأساسية'}</TabsTrigger>
                <TabsTrigger value="employment">{t?.employmentTab || 'التوظيف والمالية'}</TabsTrigger>
                <TabsTrigger value="system">{t?.systemTab || 'النظام والمحاسبية'}</TabsTrigger>
              </TabsList>

              {/* =================== TAB 1: البيانات الأساسية ================= */}
              <TabsContent value="basic" className="space-y-4 pt-4">
                <div className="space-y-4">
                  {/* الاسم ورقم الموظف */}
                  <div className="grid grid-cols-2 gap-4">
                    <FormField control={form.control} name="name" render={({ field }) => (
                      <FormItem>
                        <FormLabel>{`${t?.fullName || 'الاسم الكامل'} *`}</FormLabel>
                        <FormControl><Input placeholder="محمد أحمد" {...field} /></FormControl>
                        <FormMessage />
                      </FormItem>
                    )} />
                    <FormField control={form.control} name="employeeCode" render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.employeeCode || 'الرقم الوظيفي'}</FormLabel>
                        <FormControl><Input placeholder={t?.employeeCodePlaceholder || 'EMP-001'} {...field} /></FormControl>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>

                  {/* الوظيفة والبيانات الشخصية */}
                  <div className="grid grid-cols-2 gap-4">
                    <FormField control={form.control} name="businessRole" render={({ field }) => (
                      <FormItem>
                        <FormLabel>{`${t?.businessRoleLabel || 'الوظيفة'} *`}</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value} disabled={lockBusinessRole}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder={t?.businessRolePlaceholder || 'اختر الوظيفة'} />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {BUSINESS_ROLE_PRESETS.map((preset) => (
                              <SelectItem key={preset} value={preset}>{preset}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )} />
                    <FormField control={form.control} name="gender" render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.gender || 'الجنس'}</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value || ''}>
                          <FormControl><SelectTrigger><SelectValue placeholder={t?.select || 'اختر'} /></SelectTrigger></FormControl>
                          <SelectContent>
                            <SelectItem value="male">{t?.genderMale || 'ذكر'}</SelectItem>
                            <SelectItem value="female">{t?.genderFemale || 'أنثى'}</SelectItem>
                            <SelectItem value="other">{t?.genderOther || 'أخرى'}</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>

                  {/* التواريخ الشخصية */}
                  <div className="grid grid-cols-2 gap-4">
                    <FormField control={form.control} name="birthDate" render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.birthDate || 'تاريخ الميلاد'}</FormLabel>
                        <FormControl><Input type="date" {...field} /></FormControl>
                        <FormMessage />
                      </FormItem>
                    )} />
                    <FormField control={form.control} name="nationalId" render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.nationalId || 'الرقم الوطني'}</FormLabel>
                        <FormControl><Input placeholder={t?.nationalId || 'الرقم الوطني'} {...field} /></FormControl>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>

                  {/* معلومات الاتصال */}
                  <div className="border-t pt-4">
                    <h3 className="font-semibold mb-3 text-sm">{t?.contactInfo || 'معلومات الاتصال'}</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField control={form.control} name="workEmail" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.workEmail || 'البريد الوظيفي'}</FormLabel>
                          <FormControl><Input type="email" placeholder={t?.workEmailPlaceholder || 'name@company.com'} {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="phone" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.phoneLabel || 'الهاتف'}</FormLabel>
                          <FormControl><Input placeholder={t?.phonePlaceholder || '09xxxxxxxx'} {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                  </div>

                  {/* معلومات الطوارئ */}
                  <div className="border-t pt-4">
                    <h3 className="font-semibold mb-3 text-sm">{t?.emergencyContact || 'جهة الاتصال في حالة الطوارئ'}</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField control={form.control} name="emergencyContactName" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.name || 'الاسم'}</FormLabel>
                          <FormControl><Input placeholder={t?.namePlaceholder || 'الاسم'} {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="emergencyContactPhone" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.phoneLabel || 'الهاتف'}</FormLabel>
                          <FormControl><Input placeholder={t?.phonePlaceholder || '09xxxxxxxx'} {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                  </div>

                  {/* معلومات العمل الإضافية */}
                  <div className="border-t pt-4">
                    <h3 className="font-semibold mb-3 text-sm">{t?.workInfo || 'معلومات العمل'}</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField control={form.control} name="hireDate" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.hireDate || 'تاريخ التعيين'}</FormLabel>
                          <FormControl><Input type="date" {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="department" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.department || 'القسم'}</FormLabel>
                          <Select
                            value={field.value && field.value.length > 0 ? field.value : 'none'}
                            onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}
                          >
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder={t?.departmentPlaceholder || 'اختر القسم'} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="none">{t?.select || 'غير محدد'}</SelectItem>
                              {availableDepartments.map((department) => (
                                <SelectItem key={department} value={department}>{department}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                    <div className="grid grid-cols-2 gap-4 mt-4">
                      <FormField control={form.control} name="managerName" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.managerName || 'المدير المباشر'}</FormLabel>
                          <FormControl><Input placeholder={t?.managerNamePlaceholder || 'اسم المدير'} {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="workLocation" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.workLocation || 'موقع العمل'}</FormLabel>
                          <Select
                            value={field.value && field.value.length > 0 ? field.value : 'none'}
                            onValueChange={(value) => field.onChange(value === 'none' ? '' : value)}
                          >
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder={t?.workLocationPlaceholder || 'الفرع / الموقع'} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="none">{t?.select || 'غير محدد'}</SelectItem>
                              {warehouseLocationOptions.map((option) => (
                                <SelectItem key={option.label} value={option.value}>
                                  {option.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                  </div>
                </div>
              </TabsContent>

              {/* =================== TAB 2: التوظيف والمالية ================= */}
              <TabsContent value="employment" className="space-y-4 pt-4">
                <div className="space-y-4">
                  {/* نوع التوظيف والحالة */}
                  <div className="grid grid-cols-2 gap-4">
                    <FormField control={form.control} name="status" render={({ field }) => (
                      <FormItem>
                        <FormLabel>{`${t?.status || 'حالة التوظيف'} *`}</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl><SelectTrigger><SelectValue /></SelectTrigger></FormControl>
                          <SelectContent>
                            <SelectItem value="permanent">{t?.statusPermanent || 'دائم'}</SelectItem>
                            <SelectItem value="temporary">{t?.statusTemporary || 'مؤقت'}</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )} />
                    <FormField control={form.control} name="defaultShift" render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.defaultShift || 'الوردية الافتراضية'}</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl><SelectTrigger><SelectValue /></SelectTrigger></FormControl>
                          <SelectContent>
                            <SelectItem value="none">{t?.shiftNone || 'بدون'}</SelectItem>
                            <SelectItem value="first">{t?.shiftFirst || 'الأولى'}</SelectItem>
                            <SelectItem value="second">{t?.shiftSecond || 'الثانية'}</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>

                  {/* الراتب */}
                  <div className="border-t pt-4">
                    <h3 className="font-semibold mb-3 text-sm">{t?.salarySection || 'بيانات الراتب'}</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField control={form.control} name="salaryType" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{`${t?.salaryType || 'نوع الراتب'} *`}</FormLabel>
                          <Select onValueChange={field.onChange} value={field.value} disabled={watchStatus === 'temporary'}>
                            <FormControl><SelectTrigger><SelectValue /></SelectTrigger></FormControl>
                            <SelectContent>
                              <SelectItem value="monthly">{t?.salaryTypeMonthly || 'شهري'}</SelectItem>
                              <SelectItem value="daily">{t?.salaryTypeDaily || 'يومي'}</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="salary" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{`${t?.salaryRate || 'قيمة الراتب'} *`}</FormLabel>
                          <FormControl><Input type="number" step="0.01" placeholder="0" {...field} disabled={watchStatus === 'temporary'} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                    <div className="grid grid-cols-1 gap-4 mt-4">
                      <FormField control={form.control} name="allowedPto" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.allowedPto || 'الإجازات السنوية المسموحة'}</FormLabel>
                          <FormControl><Input type="number" placeholder="15" {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                  </div>

                  {/* بيانات مندوب المبيعات (مشروط) */}
                  {isSalesBusinessRole(watchBusinessRole) && (
                    <div className="border-t pt-4">
                      <h3 className="font-semibold mb-3 text-sm">{t?.salesRepSection || t?.salesRepRoleName || 'بيانات مندوب المبيعات'}</h3>
                      <div className="grid grid-cols-2 gap-4">
                        <FormField control={form.control} name="region" render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.regionLabel || 'المنطقة'}</FormLabel>
                            <FormControl><Input placeholder="المنطقة" {...field} /></FormControl>
                            <FormMessage />
                          </FormItem>
                        )} />
                        <FormField control={form.control} name="commissionRate" render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.commissionRateLabel || 'نسبة العمولة (%)'}</FormLabel>
                            <FormControl><Input type="number" step="0.01" min={0} max={100} placeholder="0" {...field} /></FormControl>
                            <FormMessage />
                          </FormItem>
                        )} />
                      </div>
                    </div>
                  )}

                  {/* المستودعات */}
                  <div className="border-t pt-4">
                    <h3 className="font-semibold mb-3 text-sm">{t?.warehousesSection || 'المستودعات المصرح بها'}</h3>
                    <FormField control={form.control} name="warehouseIds" render={({ field }) => (
                      <FormItem>
                        <div className="space-y-2 border rounded-md p-3 bg-muted/30">
                          {warehouses.length > 0 ? (
                            warehouses.map((wh: any) => (
                              <div key={wh.id} className="flex items-center space-x-2">
                                <input
                                  type="checkbox"
                                  id={`employee-dialog-warehouse-${wh.id}`}
                                  checked={(field.value || []).includes(wh.id)}
                                  onChange={(e) => {
                                    const current = field.value || [];
                                    if (e.target.checked) {
                                      field.onChange([...current, wh.id]);
                                    } else {
                                      field.onChange(current.filter((id: string) => id !== wh.id));
                                    }
                                  }}
                                  className="rounded"
                                />
                                <label htmlFor={`employee-dialog-warehouse-${wh.id}`} className="text-sm cursor-pointer">
                                  {wh.name}
                                </label>
                              </div>
                            ))
                          ) : (
                            <p className="text-xs text-muted-foreground">{t?.noWarehouses || 'لا توجد مستودعات متاحة'}</p>
                          )}
                        </div>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>
                </div>
              </TabsContent>

              {/* =================== TAB 3: النظام والمحاسبية ================= */}
              <TabsContent value="system" className="space-y-4 pt-4">
                <div className="space-y-4">
                  {/* بيانات تسجيل الدخول */}
                  <div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                    <h3 className="font-semibold mb-3 text-sm">{t?.loginSection || 'بيانات تسجيل الدخول'}</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField control={form.control} name="username" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{`${t?.username || 'اسم المستخدم'} *`}</FormLabel>
                          <FormControl><Input placeholder={t?.usernamePlaceholder || 'john.doe'} {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="password" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{`${t?.newPassword || 'كلمة المرور'} *`}</FormLabel>
                          <FormControl><Input type="password" placeholder={t?.passwordPlaceholder || '••••••••'} {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                  </div>

                  {/* الصلاحيات والأدوار */}
                  <div className="bg-purple-50 dark:bg-purple-950/20 border border-purple-200 dark:border-purple-800 rounded-lg p-4">
                    <h3 className="font-semibold mb-3 text-sm">{t?.roleSection || 'الصلاحيات والأدوار'}</h3>
                    <FormField control={form.control} name="role" render={({ field }) => (
                      <FormItem>
                        <FormLabel>{`${t?.systemRoleLabel || 'صلاحيات النظام'} *`}</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl><SelectTrigger><SelectValue /></SelectTrigger></FormControl>
                          <SelectContent>
                            <SelectItem value="admin">مدير</SelectItem>
                            <SelectItem value="employee">موظف</SelectItem>
                            <SelectItem value="pos">POS</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )} />
                    <FormField control={form.control} name="permissionProfileId" render={({ field }) => (
                      <FormItem className="mt-4">
                        <FormLabel>{'نوع الموظف / ملف الصلاحيات'}</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value || ''}>
                          <FormControl><SelectTrigger><SelectValue placeholder="اختر نوع الموظف" /></SelectTrigger></FormControl>
                          <SelectContent>
                            {permissionProfiles.filter((profile) => profile.role === watchRole).map((profile) => (
                              <SelectItem key={profile.id} value={profile.id}>{profile.name}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <p className="text-xs text-muted-foreground">{'هذا الحقل يربط الموظف بنوع وصلاحيات مخزنة في الإعدادات العامة.'}</p>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>

                  {/* الحسابات المحاسبية */}
                  <div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
                    <h3 className="font-semibold mb-3 text-sm">{t?.accountingSection || 'الحسابات المحاسبية'}</h3>
                    <div className="grid grid-cols-2 gap-4 mb-4">
                      <FormField control={form.control} name="employeeCashAccountCode" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{'الصندوق المرتبط'}</FormLabel>
                          <FormControl><Input value={field.value || 'سيتم إنشاؤه تلقائياً عند حفظ الموظف'} readOnly disabled className="bg-muted" /></FormControl>
                          <p className="text-xs text-muted-foreground">{'يتم إنشاء صندوق فرعي خاص بالموظف تلقائياً في شجرة الحسابات عند إنشاء البطاقة.'}</p>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                      <FormField control={form.control} name="payrollExpenseAccountCode" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.payrollExpenseAccount || 'حساب مصروف الرواتب'}</FormLabel>
                          <FormControl>
                            <AccountCodeSelector
                              value={field.value}
                              options={payrollExpenseOptions}
                              placeholder={t?.payrollExpensePlaceholder || '5210 - رواتب'}
                              onValueChange={field.onChange}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="payrollLiabilityAccountCode" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.payrollLiabilityAccount || 'حساب رواتب مستحقة'}</FormLabel>
                          <FormControl>
                            <AccountCodeSelector
                              value={field.value}
                              options={payrollLiabilityOptions}
                              placeholder={t?.payrollLiabilityPlaceholder || '2160 - مستحقة'}
                              onValueChange={field.onChange}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="employeeAdvanceAccountCode" render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.employeeAdvanceAccount || 'حساب سلف الموظفين'}</FormLabel>
                          <FormControl>
                            <AccountCodeSelector
                              value={field.value}
                              options={employeeAdvanceOptions}
                              placeholder={t?.employeeAdvancePlaceholder || '1150 - سلف'}
                              onValueChange={field.onChange}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                  </div>
                </div>
              </TabsContent>
            </Tabs>

            <DialogFooter className="gap-2">
              <Button variant="outline" type="button" onClick={() => onOpenChange(false)}>{t?.cancel || 'إلغاء'}</Button>
              <Button type="submit" disabled={isPending}>
                {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                {t?.createEmployee || 'إنشاء موظف'}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
