
"use client";

import { useState, useTransition, useEffect, useMemo } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { format, getMonth, getYear } from "date-fns";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
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 {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import EmployeeAddDialog from "@/components/admin/employee-add-dialog";
import { formatCurrency } from '@/lib/currency-formatter';
import { MoreHorizontal, PlusCircle, Loader2, Wallet } from "lucide-react";
import { type ChartOfAccount, type Employee, type EmployeePermissionProfile, type JournalEntry } from "@/lib/types";
import AccountCodeSelector from '@/components/admin/account-code-selector';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form";
import { useToast } from "@/hooks/use-toast";
import { useDocumentLock } from '@/hooks/use-document-lock';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';
import {
  handleUpdateEmployee,
  handleDeleteEmployee,
  handleBuildEmployeeCashbox,
  handleTransferEmployeeCashboxToMain,
  handleBuildEmployeeChecksAccount,
  handleTransferEmployeeChecksToMain,
} from "@/lib/actions";


type Translation = {
    title: string;
    description: string;
    addEmployee: string;
    name: string;
    salary: string;
    checkedIn: string;
    monthlyDeductions: string;
    monthlyBonuses: string;
    deleteDialogTitle: string;
    deleteDialogDescription: string;
    delete: string;
    editEmployee: string;
    viewStatement: string;
    advancesDeductions: string;
    addDialogTitle: string;
    addDialogDescription: string;
    editDialogTitle: string;
    editDialogDescription: string;
    fullName: string;
    username: string;
    newPassword: string;
    passwordDescription: string;
    salaryType: string;
    salaryRate: string;
    status: string;
    defaultShift: string;
    allowedPto: string;
    saveChanges: string;
    createEmployee: string;
    salaryTypeMonthly: string;
    salaryTypeDaily: string;
    statusPermanent: string;
    statusTemporary: string;
    shiftNone: string;
    shiftFirst: string;
    shiftSecond: string;
    deductionDetails: string;
    bonusDetails: string;
    menuLabel: string;
    basicTab?: string;
    employmentTab?: string;
    systemTab?: string;
    employeeCode?: string;
    employeeCodePlaceholder?: string;
    gender?: string;
    select?: string;
    genderMale?: string;
    genderFemale?: string;
    genderOther?: string;
    birthDate?: string;
    nationalId?: string;
    contactInfo?: string;
    workEmail?: string;
    workEmailPlaceholder?: string;
    phonePlaceholder?: string;
    emergencyContact?: string;
    namePlaceholder?: string;
    workInfo?: string;
    hireDate?: string;
    department?: string;
    departmentPlaceholder?: string;
    managerName?: string;
    managerNamePlaceholder?: string;
    workLocation?: string;
    workLocationPlaceholder?: string;
    salarySection?: string;
    salesRepSection?: string;
    warehousesSection?: string;
    noWarehouses?: string;
    loginSection?: string;
    usernamePlaceholder?: string;
    passwordPlaceholder?: string;
    roleSection?: string;
    accountingSection?: string;
    payrollExpenseAccount?: string;
    payrollExpensePlaceholder?: string;
    payrollLiabilityAccount?: string;
    payrollLiabilityPlaceholder?: string;
    employeeAdvanceAccount?: string;
    employeeAdvancePlaceholder?: string;
    cancel?: string;
    actionsLabel?: string;
    roleLabel?: string;
    roleAdmin?: string;
    roleEmployee?: string;
    rolePos?: string;
    systemRoleLabel?: string;
    businessRoleLabel?: string;
    businessRolePlaceholder?: string;
    phoneLabel?: string;
    regionLabel?: string;
    commissionRateLabel?: string;
    salesRepRoleName?: string;
};

type EmployeeCashboxBalance = {
    employeeId: string;
    cashBalance: number;
    checksBalance: number;
};

type EmployeeWithStats = Employee & {
    totalDeductions: number;
    deductionRecords: { description: string; amount: number }[];
    totalBonuses: number;
    bonusRecords: { description: string; amount: number }[];
    attendedDays: number;
};
const updateEmployeeSchema = 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, "الوظيفة مطلوبة."),
  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']),
  password: z.string().min(6, "يجب أن تحتوي كلمة المرور على 6 أحرف على الأقل.").optional().or(z.literal('')),
  role: z.enum(['admin', 'employee', 'pos']).optional(),
  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';
}

function getDefaultProfileId(permissionProfiles: EmployeePermissionProfile[], role: 'admin' | 'employee' | 'pos') {
  return permissionProfiles.find((profile) => profile.role === role)?.id || '';
}

function buildEmployeeCashboxBalances(
  employees: Employee[],
  journalEntries: JournalEntry[]
): EmployeeCashboxBalance[] {
  const balanceByCode = new Map<string, number>();

  journalEntries.forEach((entry) => {
    (entry.lines || []).forEach((line) => {
      const code = String(line.accountCode || '').trim();
      if (!code) return;
      const nextBalance = (balanceByCode.get(code) || 0) + Number(line.debit || 0) - Number(line.credit || 0);
      balanceByCode.set(code, Math.round(nextBalance * 100) / 100);
    });
  });

  return employees.map((employee) => ({
    employeeId: employee.id,
    cashBalance: employee.employeeCashAccountCode ? balanceByCode.get(String(employee.employeeCashAccountCode).trim()) || 0 : 0,
    checksBalance: employee.employeeChecksAccountCode ? balanceByCode.get(String(employee.employeeChecksAccountCode).trim()) || 0 : 0,
  }));
}

function DeleteConfirmationDialog({ employee, t, onConfirm }: { employee: Employee; t: Translation; onConfirm: () => void }) {
  return (
    <AlertDialog>
      <AlertDialogTrigger asChild>
        <div className="relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50 text-destructive focus:text-destructive w-full">{t.delete}</div>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{t.deleteDialogTitle}</AlertDialogTitle>
          <AlertDialogDescription>
            {t.deleteDialogDescription.replace('{name}', employee.name)}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>{t.cancel ?? 'إلغاء'}</AlertDialogCancel>
          <AlertDialogAction onClick={onConfirm} className="bg-destructive hover:bg-destructive/90">{t.delete}</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}


function EditEmployeeDialog({ employee, t, onFinished, onSavedEmployee, warehouses = [], chartAccounts = [], permissionProfiles = [], cashboxBalance = 0, checksBalance = 0, currencySymbol = '' }: { employee: Employee; t: Translation, onFinished: () => void, onSavedEmployee?: (employee: Employee) => void, warehouses?: any[], chartAccounts?: ChartOfAccount[], permissionProfiles?: EmployeePermissionProfile[], cashboxBalance?: number, checksBalance?: number, currencySymbol?: string }) {
    const [isPending, startTransition] = useTransition();
    const router = useRouter();
    const { toast } = useToast();
  const { lockStatus, acquireLock } = useDocumentLock('employee', employee.id);
  const isEditLocked = lockStatus.isLocked;
    const form = useForm<z.infer<typeof updateEmployeeSchema>>({
        resolver: zodResolver(updateEmployeeSchema),
        defaultValues: {
            name: employee.name,
          employeeCode: employee.employeeCode || '',
          nationalId: employee.nationalId || '',
          workEmail: employee.workEmail || '',
          birthDate: employee.birthDate || '',
          gender: employee.gender,
          hireDate: employee.hireDate || '',
          department: employee.department || '',
          managerName: employee.managerName || '',
          workLocation: employee.workLocation || '',
          emergencyContactName: employee.emergencyContactName || '',
          emergencyContactPhone: employee.emergencyContactPhone || '',
          employeeCashAccountCode: employee.employeeCashAccountCode || '',
          payrollExpenseAccountCode: employee.payrollExpenseAccountCode || '5210',
          payrollLiabilityAccountCode: employee.payrollLiabilityAccountCode || '2160',
          employeeAdvanceAccountCode: employee.employeeAdvanceAccountCode || '1150',
        businessRole: employee.businessRole || 'موظف',
        phone: employee.phone || '',
        region: employee.region || '',
        commissionRate: employee.commissionRate ?? undefined,
            salaryType: employee.salaryType,
            salary: employee.salary,
            allowedPto: employee.allowedPto,
            status: employee.status,
            defaultShift: employee.defaultShift,
            password: "",
            role: employee.role || 'employee',
            permissionProfileId: employee.permissionProfileId || getDefaultProfileId(permissionProfiles, employee.role || 'employee'),
            warehouseIds: 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(() => {
        // فقط قم بتعيين الراتب إلى 0 إذا كان الموظف دائماً قبل ذلك وتم تغييره إلى مؤقت
        if (watchStatus === 'temporary' && employee.status === 'permanent') {
            form.setValue('salary', 0);
            form.setValue('salaryType', 'daily');
        }
    }, [watchStatus, form, employee.status]);

    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]);

    async function onSubmit(values: z.infer<typeof updateEmployeeSchema>) {
    if (isEditLocked) {
      const reacquired = await acquireLock();
      if (reacquired) {
        startTransition(async () => {
          const result = await handleUpdateEmployee(employee.id, values);
          if (result.success) {
            if ('employee' in result && result.employee) {
              onSavedEmployee?.(result.employee as Employee);
            }
            toast({
              title: 'تم الحفظ',
              description: 'تم تحديث بيانات الموظف بنجاح.',
            });
            router.refresh();
            onFinished();
          } else {
            toast({
              title: 'خطأ',
              description: result.error || 'تعذر تحديث بيانات الموظف.',
              variant: 'destructive'
            });
          }
        });
        return;
      }

      const lockedByUser = lockStatus.lockedBy?.userName || 'مستخدم آخر';
      const lockedAtTime = lockStatus.lockedBy?.lockedAt 
        ? new Date(lockStatus.lockedBy.lockedAt).toLocaleTimeString('ar-SA')
        : '';
      
      toast({
        title: 'خطأ',
        description: `هذا السجل مقفول من قبل ${lockedByUser}${lockedAtTime ? ` منذ ${lockedAtTime}` : ''} ولا يمكن تعديله. حاول لاحقاً.`,
        variant: 'destructive',
      });
      return;
    }

        startTransition(async () => {
            const result = await handleUpdateEmployee(employee.id, values);
            if (result.success) {
          if ('employee' in result && result.employee) {
            onSavedEmployee?.(result.employee as Employee);
          }
          toast({
            title: 'تم الحفظ',
            description: 'تم تحديث بيانات الموظف بنجاح.',
          });
                router.refresh();
                onFinished();
            } else {
          toast({
            title: 'خطأ',
            description: result.error || 'تعذر تحديث بيانات الموظف.',
            variant: "destructive"
          });
            }
        });
    }

    function onBuildCashbox() {
        startTransition(async () => {
            const result = await handleBuildEmployeeCashbox(employee.id);
            if (result.success) {
                toast({
                    title: 'تم إنشاء الصندوق',
                    description: `تم ربط الصندوق ${String(result.account?.code || '')} بالموظف بنجاح.`,
                });
                router.refresh();
                onFinished();
                return;
            }

            toast({
                title: 'خطأ',
                description: result.error || 'تعذر إنشاء صندوق الموظف.',
                variant: 'destructive',
            });
        });
    }

    function onTransferCashbox() {
        startTransition(async () => {
            const result = await handleTransferEmployeeCashboxToMain(employee.id, { source: 'employee-table' });
            if (result.success) {
                toast({
                    title: 'تم الترحيل',
                    description: `تم ترحيل مبلغ ${Number(result.amount || 0).toFixed(2)} إلى الصندوق الرئيسي.`,
                });
                router.refresh();
                onFinished();
                return;
            }

            toast({
                title: 'خطأ',
                description: result.error || 'تعذر ترحيل رصيد صندوق الموظف.',
                variant: 'destructive',
            });
        });
    }
    
      function onBuildChecks() {
        startTransition(async () => {
          const result = await handleBuildEmployeeChecksAccount(employee.id);
          if (result.success) {
            toast({
              title: 'تم إنشاء حساب الشيكات',
              description: `تم ربط الحساب ${String(result.account?.code || '')} بالموظف بنجاح.`,
            });
            router.refresh();
            onFinished();
            return;
          }
          toast({ title: 'خطأ', description: result.error || 'تعذر إنشاء حساب الشيكات.', variant: 'destructive' });
        });
      }

      function onTransferChecks() {
        startTransition(async () => {
          const result = await handleTransferEmployeeChecksToMain(employee.id);
          if (result.success) {
            toast({
              title: 'تم تسليم الشيكات',
              description: `تم ترحيل ${Number(result.amount || 0).toFixed(2)} من شيكات الموظف إلى أوراق القبض الرئيسي.`,
            });
            router.refresh();
            onFinished();
            return;
          }
          toast({ title: 'خطأ', description: result.error || 'تعذر ترحيل شيكات الموظف.', variant: 'destructive' });
        });
      }
    return (
        <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
                <DialogTitle>{t.editDialogTitle.replace('{name}', employee.name)}</DialogTitle>
                <DialogDescription>{t.editDialogDescription}</DialogDescription>
            </DialogHeader>
            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <DocumentLockBanner lockStatus={lockStatus} />
                    <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>الاسم الكامل</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}>
                                  <FormControl><SelectTrigger><SelectValue /></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>حالة التوظيف</FormLabel>
                                <Select onValueChange={field.onChange} value={field.value}>
                                  <FormControl><SelectTrigger><SelectValue /></SelectTrigger></FormControl>
                                  <SelectContent>
                                    <SelectItem value="permanent">دائم</SelectItem>
                                    <SelectItem value="temporary">مؤقت</SelectItem>
                                  </SelectContent>
                                </Select>
                                <FormMessage />
                              </FormItem>
                            )} />
                            <FormField control={form.control} name="defaultShift" render={({ field }) => (
                              <FormItem>
                                <FormLabel>الوردية الافتراضية</FormLabel>
                                <Select onValueChange={field.onChange} value={field.value}>
                                  <FormControl><SelectTrigger><SelectValue /></SelectTrigger></FormControl>
                                  <SelectContent>
                                    <SelectItem value="none">بدون</SelectItem>
                                    <SelectItem value="first">الأولى</SelectItem>
                                    <SelectItem value="second">الثانية</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">شهري</SelectItem>
                                      <SelectItem value="daily">يومي</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>المنطقة</FormLabel>
                                    <FormControl><Input placeholder="المنطقة" {...field} /></FormControl>
                                    <FormMessage />
                                  </FormItem>
                                )} />
                                <FormField control={form.control} name="commissionRate" render={({ field }) => (
                                  <FormItem>
                                    <FormLabel>نسبة العمولة (%)</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={`warehouse-edit-${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={`warehouse-edit-${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>
                            <FormItem>
                              <FormLabel>{t.username}</FormLabel>
                              <FormControl><Input value={employee.username} readOnly disabled className="bg-gray-100" /></FormControl>
                            </FormItem>
                            <div className="mt-4">
                              <FormField control={form.control} name="password" render={({ field }) => (
                                <FormItem>
                                  <FormLabel>{`${t.newPassword} (${t.passwordDescription})`}</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>
                                <FormDescription>{'الصلاحيات التفصيلية لهذا النوع تُدار من صفحة الإعدادات العامة.'}</FormDescription>
                                <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 space-y-4">
                            <h3 className="font-semibold mb-3 text-sm">{t.accountingSection ?? 'الحسابات المحاسبية'}</h3>
                            <div className="grid grid-cols-2 gap-4">
                              <FormField control={form.control} name="employeeCashAccountCode" render={({ field }) => (
                                <FormItem>
                                  <FormLabel>{'الصندوق المرتبط'}</FormLabel>
                                  <FormControl><Input value={field.value || 'لا يوجد صندوق مرتبط'} readOnly disabled className="bg-muted" /></FormControl>
                                  <FormDescription>{'تُسجَّل المبيعات النقدية لهذا الموظف على هذا الصندوق الفرعي بدلاً من الصندوق الرئيسي.'}</FormDescription>
                                  <FormMessage />
                                </FormItem>
                              )} />
                              <div className="rounded-md border bg-background p-3 text-sm">
                                <div className="flex items-center justify-between gap-3">
                                  <div>
                                    <p className="font-medium">{'الرصيد الحالي'}</p>
                                    <p className="text-2xl font-semibold">{cashboxBalance.toFixed(2)}{currencySymbol ? ` ${currencySymbol}` : ''}</p>
                                  </div>
                                  <Wallet className="h-5 w-5 text-muted-foreground" />
                                </div>
                                <div className="mt-3 flex flex-wrap gap-2">
                                  {!employee.employeeCashAccountCode ? (
                                    <Button type="button" variant="outline" onClick={onBuildCashbox} disabled={isPending}>
                                      {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                                      {'إنشاء صندوق الموظف'}
                                    </Button>
                                  ) : (
                                    <Button type="button" variant="outline" onClick={onTransferCashbox} disabled={isPending || cashboxBalance <= 0}>
                                      {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                                      {'ترحيل إلى الصندوق الرئيسي'}
                                    </Button>
                                  )}
                                </div>
                              </div>
                            </div>
                            <div className="grid grid-cols-3 gap-4">
                                {/* شيكات الموظف */}
                                <div className="col-span-2 grid grid-cols-2 gap-4 border rounded-lg p-3 bg-muted/20">
                                  <div>
                                    <p className="text-xs font-medium mb-1">{'حساب الشيكات الواردة'}</p>
                                    <p className="text-sm text-muted-foreground">{employee.employeeChecksAccountCode || 'لا يوجد حساب شيكات مرتبط'}</p>
                                    <p className="text-xs text-muted-foreground mt-1">{'تُسجَّل الشيكات المستلمة على هذا الحساب بدلاً من أوراق القبض الرئيسي.'}</p>
                                  </div>
                                  <div className="rounded-md border bg-background p-3 text-sm">
                                    <div className="flex items-center justify-between gap-2">
                                      <div>
                                        <p className="font-medium">{'رصيد الشيكات'}</p>
                                        <p className="text-xl font-semibold">{checksBalance.toFixed(2)}{currencySymbol ? ` ${currencySymbol}` : ''}</p>
                                      </div>
                                    </div>
                                    <div className="mt-2 flex flex-wrap gap-2">
                                      {!employee.employeeChecksAccountCode ? (
                                        <Button type="button" variant="outline" size="sm" onClick={onBuildChecks} disabled={isPending}>
                                          {isPending && <Loader2 className="me-2 h-3 w-3 animate-spin" />}
                                          {'إنشاء حساب الشيكات'}
                                        </Button>
                                      ) : (
                                        <Button type="button" variant="outline" size="sm" onClick={onTransferChecks} disabled={isPending || checksBalance <= 0}>
                                          {isPending && <Loader2 className="me-2 h-3 w-3 animate-spin" />}
                                          {'تسليم للمدير'}
                                        </Button>
                                      )}
                                    </div>
                                  </div>
                                </div>
                              </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={onFinished}>{t.cancel ?? 'إلغاء'}</Button>
                      <Button type="submit" disabled={isPending}>
                            {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                            {t.saveChanges}
                        </Button>
                    </DialogFooter>
                </form>
            </Form>
        </DialogContent>
    );
}

export default function EmployeeTable({ employees, month, year, t, currencySymbol = '$', warehouses = [], chartAccounts = [], permissionProfiles = [], journalEntries = [] }: { employees: EmployeeWithStats[], month: number, year: number, t: Translation, currencySymbol?: string, warehouses?: any[], chartAccounts?: ChartOfAccount[], permissionProfiles?: EmployeePermissionProfile[], journalEntries?: JournalEntry[] }) {
  const [dialogState, setDialogState] = useState<{ open: boolean; view: 'add' | 'edit'; employee?: Employee }>({ open: false, view: 'add' });
  const [localEmployees, setLocalEmployees] = useState<EmployeeWithStats[]>(employees);

  const [isPending, startTransition] = useTransition();
  const router = useRouter();
  const { toast } = useToast();

  const monthName = format(new Date(year, month), 'MMMM');
  const cashboxBalances = useMemo(() => buildEmployeeCashboxBalances(localEmployees, journalEntries), [localEmployees, journalEntries]);
  const cashboxBalanceMap = useMemo(() => new Map(cashboxBalances.map((entry) => [entry.employeeId, entry])), [cashboxBalances]);

  useEffect(() => {
    setLocalEmployees(employees);
  }, [employees]);

  function onEmployeeSaved(updatedEmployee: Employee) {
    setLocalEmployees((prev) =>
      prev.map((entry) =>
        String(entry.id || '') === String(updatedEmployee.id || '')
          ? ({ ...entry, ...updatedEmployee } as EmployeeWithStats)
          : entry
      )
    );

    setDialogState((prev) => {
      if (prev.view !== 'edit' || !prev.employee) return prev;
      if (String(prev.employee.id || '') !== String(updatedEmployee.id || '')) return prev;
      return { ...prev, employee: { ...prev.employee, ...updatedEmployee } };
    });
  }

  function onDelete(employeeId: string) {
     startTransition(async () => {
      const result = await handleDeleteEmployee(employeeId);
      if (result.success) {
        toast({
          title: 'تم الحذف',
          description: 'تم حذف الموظف بنجاح.',
        });
        router.refresh();
      } else {
        toast({
          title: 'خطأ',
          description: result.error || 'تعذر حذف الموظف.',
          variant: "destructive",
        });
      }
    });
  }

  function onBuildCashbox(employeeId: string) {
    startTransition(async () => {
      const result = await handleBuildEmployeeCashbox(employeeId);
      if (result.success) {
        toast({
          title: 'تم إنشاء الصندوق',
          description: `تم إنشاء وربط الصندوق ${String(result.account?.code || '')}.`,
        });
        router.refresh();
        return;
      }

      toast({
        title: 'خطأ',
        description: result.error || 'تعذر إنشاء صندوق الموظف.',
        variant: 'destructive',
      });
    });
  }

  function onTransferCashbox(employeeId: string) {
    startTransition(async () => {
      const result = await handleTransferEmployeeCashboxToMain(employeeId, { source: 'employee-table' });
      if (result.success) {
        toast({
          title: 'تم الترحيل',
          description: `تم ترحيل مبلغ ${Number(result.amount || 0).toFixed(2)} إلى الصندوق الرئيسي.`,
        });
        router.refresh();
        return;
      }

        function onBuildChecksAccount(employeeId: string) {
          startTransition(async () => {
            const result = await handleBuildEmployeeChecksAccount(employeeId);
            if (result.success) {
              toast({ title: 'تم إنشاء حساب الشيكات', description: `تم إنشاء الحساب ${String(result.account?.code || '')}.` });
              router.refresh();
              return;
            }
            toast({ title: 'خطأ', description: result.error || 'تعذر إنشاء حساب الشيكات.', variant: 'destructive' });
          });
        }

        function onTransferChecks(employeeId: string) {
          startTransition(async () => {
            const result = await handleTransferEmployeeChecksToMain(employeeId);
            if (result.success) {
              toast({ title: 'تم تسليم الشيكات', description: `تم ترحيل ${Number(result.amount || 0).toFixed(2)} إلى أوراق القبض.` });
              router.refresh();
              return;
            }
            toast({ title: 'خطأ', description: result.error || 'تعذر ترحيل شيكات الموظف.', variant: 'destructive' });
          });
        }
      toast({
        title: 'خطأ',
        description: result.error || 'تعذر ترحيل رصيد صندوق الموظف.',
        variant: 'destructive',
      });
    });
  }
  
  const closeDialog = () => setDialogState({ ...dialogState, open: false });

  return (
    <Card>
       <CardHeader className="flex flex-row items-center">
        <div className="grid gap-2">
            <CardTitle>{t.title.replace('{monthName}', monthName).replace('{year}', String(year))}</CardTitle>
            <CardDescription>{t.description}</CardDescription>
        </div>
        <div className="ms-auto flex items-center gap-2">
            <Button size="sm" className="gap-1" onClick={() => setDialogState({ open: true, view: 'add' })}>
                <PlusCircle className="h-3.5 w-3.5" />
                <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
                    {t.addEmployee}
                </span>
            </Button>
        </div>
      </CardHeader>
      <CardContent>
        <EmployeeAddDialog
          open={dialogState.open && dialogState.view === 'add'}
          onOpenChange={(open) => setDialogState(open ? { open: true, view: 'add' } : { open: false, view: 'add' })}
          t={t}
          warehouses={warehouses}
          chartAccounts={chartAccounts}
          permissionProfiles={permissionProfiles}
        />
        <Dialog open={dialogState.open && dialogState.view === 'edit'} onOpenChange={(open) => { if (!open) closeDialog(); }}>
           {dialogState.view === 'edit' && dialogState.employee && (
             <EditEmployeeDialog employee={dialogState.employee} t={t} onFinished={closeDialog} onSavedEmployee={onEmployeeSaved} warehouses={warehouses} chartAccounts={chartAccounts} permissionProfiles={permissionProfiles} cashboxBalance={cashboxBalanceMap.get(dialogState.employee.id)?.cashBalance || 0} checksBalance={cashboxBalanceMap.get(dialogState.employee.id)?.checksBalance || 0} currencySymbol={currencySymbol} />
           )}
        </Dialog>
        <div className="mb-6 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          {localEmployees.map((employee) => {
            const empBalances = cashboxBalanceMap.get(employee.id);
            const cashBal = empBalances?.cashBalance || 0;
            const checksBal = empBalances?.checksBalance || 0;
            return (
              <div key={`cashbox-${employee.id}`} className="rounded-lg border bg-muted/20 p-4">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <p className="font-medium">{employee.name}</p>
                    <p className="text-xs text-muted-foreground">{employee.employeeCashAccountCode || 'بدون صندوق مرتبط'}</p>
                  </div>
                  <Badge variant={cashBal > 0 ? 'default' : 'secondary'}>{formatCurrency(cashBal, currencySymbol)}</Badge>
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  {!employee.employeeCashAccountCode ? (
                    <Button type="button" variant="outline" size="sm" onClick={() => onBuildCashbox(employee.id)} disabled={isPending}>
                      {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                      {'إنشاء الصندوق'}
                    </Button>
                  ) : (
                    <Button type="button" variant="outline" size="sm" asChild>
                      <Link href="/admin/dashboard">ترحيل من لوحة التحكم</Link>
                    </Button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
         <TooltipProvider>
            <Table>
            <TableHeader>
                <TableRow>
                    <TableHead className="text-start">{t.name}</TableHead>
                    <TableHead className="hidden md:table-cell text-start">{t.businessRoleLabel ?? 'الوظيفة'}</TableHead>
                    <TableHead className="text-start">{t.salary}</TableHead>
                    <TableHead className="hidden md:table-cell text-center">{t.checkedIn.replace('{monthName}', monthName)}</TableHead>
                    <TableHead className="hidden md:table-cell text-center">{t.monthlyDeductions}</TableHead>
                    <TableHead className="hidden md:table-cell text-center">{t.monthlyBonuses}</TableHead>
                    <TableHead>
                        <span className="sr-only">{t.actionsLabel ?? 'إجراءات'}</span>
                    </TableHead>
                </TableRow>
            </TableHeader>
            <TableBody>
                {localEmployees.map((employee) => {
                    const { totalDeductions, deductionRecords, totalBonuses, bonusRecords, attendedDays } = employee;

                    return (
                        <TableRow key={employee.id}>
                            <TableCell className="font-medium text-start">{employee.name}</TableCell>
                        <TableCell className="hidden md:table-cell text-start">{employee.businessRole || '-'}</TableCell>
                            <TableCell className="text-start">{formatCurrency(employee.salary, currencySymbol)} <span className="text-muted-foreground text-xs">/{employee.salaryType === 'monthly' ? 'mo' : 'day'}</span></TableCell>
                            <TableCell className="hidden md:table-cell text-center">{attendedDays}</TableCell>
                            <TableCell className="hidden md:table-cell text-center">
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <span className="text-red-600 cursor-help">{formatCurrency(totalDeductions, currencySymbol)}</span>
                                    </TooltipTrigger>
                                    {deductionRecords.length > 0 && (
                                    <TooltipContent>
                                        <div className="p-2">
                                            <h4 className="font-bold mb-2">{t.deductionDetails}</h4>
                                            <ul className="list-disc ps-4">
                                                {deductionRecords.map((rec, i) => (
                                                    <li key={i}>{rec.description}: {formatCurrency(rec.amount, currencySymbol)}</li>
                                                ))}
                                            </ul>
                                        </div>
                                    </TooltipContent>
                                    )}
                                </Tooltip>
                            </TableCell>
                            <TableCell className="hidden md:table-cell text-center">
                               <Tooltip>
                                    <TooltipTrigger asChild>
                                        <span className="text-green-600 cursor-help">{formatCurrency(totalBonuses, currencySymbol)}</span>
                                    </TooltipTrigger>
                                    {bonusRecords.length > 0 && (
                                    <TooltipContent>
                                        <div className="p-2">
                                            <h4 className="font-bold mb-2">{t.bonusDetails}</h4>
                                            <ul className="list-disc ps-4">
                                                {bonusRecords.map((rec, i) => (
                                                    <li key={i}>{rec.description}: {formatCurrency(rec.amount, currencySymbol)}</li>
                                                ))}
                                            </ul>
                                        </div>
                                    </TooltipContent>
                                    )}
                                </Tooltip>
                            </TableCell>
                            <TableCell>
                                <DropdownMenu modal={false}>
                                    <DropdownMenuTrigger asChild>
                                        <Button aria-haspopup="true" size="icon" variant="ghost" disabled={isPending}>
                                            <MoreHorizontal className="h-4 w-4" />
                                            <span className="sr-only">Toggle menu</span>
                                        </Button>
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent align="end">
                                    <DropdownMenuLabel>{t.menuLabel}</DropdownMenuLabel>
                                  <DropdownMenuItem onSelect={() => { setDialogState({ open: true, view: 'edit', employee }); }}>
                                        {t.editEmployee}
                                    </DropdownMenuItem>
                                    <DropdownMenuItem asChild>
                                        <Link href={`/admin/employee/${employee.id}/statement`} className="relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50">
                                            {t.viewStatement}
                                        </Link>
                                    </DropdownMenuItem>
                                    <DropdownMenuItem asChild>
                                        <Link href={`/admin/employee/${employee.id}/financials`} className="relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50">
                                            {t.advancesDeductions}
                                        </Link>
                                    </DropdownMenuItem>
                                    {employee.role !== 'admin' && (
                                        <DropdownMenuItem asChild>
                                            <DeleteConfirmationDialog employee={employee} t={t} onConfirm={() => onDelete(employee.id)} />
                                        </DropdownMenuItem>
                                    )}
                                    </DropdownMenuContent>
                                </DropdownMenu>
                            </TableCell>
                        </TableRow>
                    );
                })}
            </TableBody>
            </Table>
        </TooltipProvider>
      </CardContent>
    </Card>
  );
}
