'use client';

import { useEffect, useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import { handleAddListItem } from '@/lib/actions';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { type SalesRep } from '@/lib/types';
import EmployeeAddDialog from '@/components/admin/employee-add-dialog';

export default function AddCustomerDialog({ open, onOpenChange, onCustomerAdded, t, salesReps = [] }: { open: boolean; onOpenChange: (open: boolean) => void; onCustomerAdded: (customer: any) => void; t: any; salesReps?: SalesRep[] }) {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [address, setAddress] = useState('');
  const [creditLimit, setCreditLimit] = useState('');
  const [salesRepId, setSalesRepId] = useState('');
  const [isPending, setIsPending] = useState(false);
  const addSalesRepOptionValue = '__add_new_sales_rep__';
  const [runtimeSalesReps, setRuntimeSalesReps] = useState<SalesRep[]>(salesReps);
  const [employeeDialogOpen, setEmployeeDialogOpen] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    setRuntimeSalesReps(salesReps);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(salesReps)]);

  const handleAdd = async () => {
    if (!name.trim()) {
      toast({ title: t?.validationError ?? 'خطأ', description: t?.customerNameRequired ?? 'اسم الزبون مطلوب', variant: 'destructive' });
      return;
    }

    setIsPending(true);
    const result = await handleAddListItem('customer', {
      name,
      phone,
      address,
      creditLimit: creditLimit ? parseFloat(creditLimit) : 0,
      category: 'general',
      customerNumber: '', // سيتم إنشاء رقم تلقائي في الخادم
      salesRepId,
    });
    setIsPending(false);
    if (!('error' in result)) {
      toast({ title: t?.addCustomerSuccess ?? 'تمت إضافة الزبون بنجاح' });
      onCustomerAdded(result.item);
      onOpenChange(false);
      setName('');
      setPhone('');
      setAddress('');
      setCreditLimit('');
      setSalesRepId('');
    } else {
      toast({ title: t?.addCustomerError ?? 'فشل إضافة الزبون', description: result.error || '', variant: 'destructive' });
    }
  };

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t?.addCustomerTitle ?? 'إضافة زبون جديد'}</DialogTitle>
            <DialogDescription>{t?.addCustomerDescription ?? 'أدخل بيانات الزبون الجديد.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-2">
            <Input placeholder={t?.customerNameLabel ?? 'اسم الزبون'} value={name} onChange={e => setName(e.target.value)} />
            <Input placeholder={t?.customerPhoneLabel ?? 'رقم الهاتف'} value={phone} onChange={e => setPhone(e.target.value)} />
            <Input placeholder={t?.customerAddressLabel ?? 'العنوان'} value={address} onChange={e => setAddress(e.target.value)} />
            <Input placeholder={t?.customerCreditLimitLabel ?? 'الحد الائتماني'} value={creditLimit} onChange={e => setCreditLimit(e.target.value)} type="number" />
            <Select
              value={salesRepId || 'none'}
              onValueChange={(value) => {
                if (value === addSalesRepOptionValue) {
                  setEmployeeDialogOpen(true);
                  return;
                }
                setSalesRepId(value === 'none' ? '' : value);
              }}
            >
              <SelectTrigger>
                <SelectValue placeholder={t?.customerSalesRepPlaceholder ?? 'اختر مندوب المبيعات'} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">{t?.customerSalesRepNone ?? 'بدون مندوب'}</SelectItem>
                <SelectItem value={addSalesRepOptionValue}>{t?.addSalesRepInlineOption ?? 'إضافة مندوب جديد'}</SelectItem>
                {runtimeSalesReps.map((rep) => (
                  <SelectItem key={rep.id} value={rep.id}>{rep.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <DialogFooter>
            <Button onClick={handleAdd} disabled={isPending || !name}>{t?.addButton ?? 'إضافة'}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <EmployeeAddDialog
        open={employeeDialogOpen}
        onOpenChange={setEmployeeDialogOpen}
        t={t}
        defaultBusinessRole="مندوب مبيعات"
        lockBusinessRole
        onEmployeeCreated={(employee) => {
          const createdRep: SalesRep | null = employee?.id
            ? {
                id: String(employee.id),
                name: String(employee.name || '').trim(),
                phone: String(employee.phone || '').trim(),
                region: String(employee.region || '').trim(),
                commissionRate: Number.isFinite(employee.commissionRate) ? Number(employee.commissionRate) : 0,
              }
            : null;

          if (!createdRep) return;
          setRuntimeSalesReps((prev) => {
            if (prev.some((entry) => entry.id === createdRep.id)) return prev;
            return [...prev, createdRep];
          });
          setSalesRepId(createdRep.id);
        }}
      />
    </>
  );
}
