import { 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';

export default function AddSupplierDialog({ open, onOpenChange, onSupplierAdded, t }: { open: boolean; onOpenChange: (open: boolean) => void; onSupplierAdded: (supplier: any) => void; t: any }) {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [address, setAddress] = useState('');
  const [paymentTerms, setPaymentTerms] = useState('');
  const [isPending, setIsPending] = useState(false);
  const { toast } = useToast();

  const handleAdd = async () => {
    if (!name.trim()) {
      toast({ title: t?.validationError ?? 'خطأ', description: t?.supplierNameRequired ?? 'اسم المورد مطلوب', variant: 'destructive' });
      return;
    }
    
    setIsPending(true);
    const result = await handleAddListItem('supplier', {
      name,
      phone,
      address,
      paymentTerms: paymentTerms ? parseInt(paymentTerms) : 0,
      supplierNumber: '', // سيتم إنشاء رقم تلقائي في الخادم
    });
    setIsPending(false);
    if (!('error' in result)) {
      toast({ title: t?.addSupplierSuccess ?? 'تمت إضافة المورد بنجاح' });
      onSupplierAdded(result.item);
      onOpenChange(false);
      setName('');
      setPhone('');
      setAddress('');
      setPaymentTerms('');
    } else {
      toast({ title: t?.addSupplierError ?? 'فشل إضافة المورد', description: result.error || '', variant: 'destructive' });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t?.addSupplierTitle ?? 'إضافة مورد جديد'}</DialogTitle>
          <DialogDescription>
            {t?.addSupplierDescription ?? 'أدخل بيانات المورد ثم اضغط إضافة.'}
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-2">
          <Input placeholder={t?.supplierNameLabel ?? 'اسم المورد'} value={name} onChange={e => setName(e.target.value)} />
          <Input placeholder={t?.supplierPhoneLabel ?? 'رقم الهاتف'} value={phone} onChange={e => setPhone(e.target.value)} />
          <Input placeholder={t?.supplierAddressLabel ?? 'العنوان'} value={address} onChange={e => setAddress(e.target.value)} />
          <Input placeholder={t?.supplierPaymentTermsLabel ?? 'شروط الدفع (أيام)'} value={paymentTerms} onChange={e => setPaymentTerms(e.target.value)} type="number" />
        </div>
        <DialogFooter>
          <Button onClick={handleAdd} disabled={isPending || !name}>{t?.addButton ?? 'إضافة'}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
