'use client';

import { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import { handleAddCategory } from '@/lib/actions';

type CustomerCategoryLike = {
  id: string;
  name: string;
  categoryNumber?: string;
  nameEn?: string;
  discountPercent?: number;
  description?: string;
};

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  t?: any;
  onCategoryCreated?: (category: CustomerCategoryLike) => void;
};

export default function CustomerCategoryDialog({ open, onOpenChange, t, onCategoryCreated }: Props) {
  const [name, setName] = useState('');
  const [nameEn, setNameEn] = useState('');
  const [discountPercent, setDiscountPercent] = useState('0');
  const [description, setDescription] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const { toast } = useToast();

  const resetState = () => {
    setName('');
    setNameEn('');
    setDiscountPercent('0');
    setDescription('');
    setIsSaving(false);
  };

  const onSubmit = async () => {
    const trimmed = name.trim();
    if (!trimmed) {
      toast({
        title: t?.saveErrorTitle || 'خطأ',
        description: t?.categoryNameRequired || 'اسم التصنيف مطلوب.',
        variant: 'destructive',
      });
      return;
    }

    setIsSaving(true);
    const numericDiscount = Number(discountPercent || '0');
    const result = await handleAddCategory({
      name: trimmed,
      nameEn: nameEn.trim() || undefined,
      discountPercent: Number.isFinite(numericDiscount) ? numericDiscount : 0,
      description: description.trim() || undefined,
    });
    setIsSaving(false);

    if ('error' in result && result.error) {
      toast({
        title: t?.saveErrorTitle || 'خطأ',
        description: result.error,
        variant: 'destructive',
      });
      return;
    }

    const created = (result as any)?.category;
    if (created?.id && created?.name) {
      onCategoryCreated?.({
        id: String(created.id),
        name: String(created.name),
        categoryNumber: created.categoryNumber ? String(created.categoryNumber) : undefined,
        nameEn: created.nameEn ? String(created.nameEn) : undefined,
        discountPercent: Number(created.discountPercent || 0),
        description: created.description ? String(created.description) : undefined,
      });
    }

    toast({
      title: t?.saveSuccessTitle || 'تم الحفظ',
      description: t?.addCategorySuccess || 'تمت إضافة التصنيف بنجاح.',
    });

    onOpenChange(false);
    resetState();
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(nextOpen) => {
        if (!nextOpen) {
          resetState();
        }
        onOpenChange(nextOpen);
      }}
    >
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>{t?.addCategoryTitle || 'إضافة تصنيف'}</DialogTitle>
          <DialogDescription>{t?.addCategoryDescription || 'أدخل اسم التصنيف لإضافته لقائمة التصنيفات.'}</DialogDescription>
        </DialogHeader>
        <div className="space-y-2">
          <Input
            value={name}
            onChange={(event) => setName(event.target.value)}
            placeholder={t?.categoryNamePlaceholder || 'اسم التصنيف'}
            onKeyDown={(event) => {
              if (event.key === 'Enter') {
                event.preventDefault();
                void onSubmit();
              }
            }}
          />
          <Input
            value={nameEn}
            onChange={(event) => setNameEn(event.target.value)}
            placeholder={t?.categoryNameEnPlaceholder || 'الاسم الإنجليزي (اختياري)'}
          />
          <Input
            type="number"
            min={0}
            max={100}
            step="0.01"
            value={discountPercent}
            onChange={(event) => setDiscountPercent(event.target.value)}
            placeholder={t?.discountPercentPlaceholder || 'نسبة الخصم % (اختياري)'}
          />
          <Textarea
            value={description}
            onChange={(event) => setDescription(event.target.value)}
            placeholder={t?.descriptionPlaceholder || 'وصف مختصر (اختياري)'}
            rows={3}
          />
        </div>
        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving}>
            {t?.cancel || 'إلغاء'}
          </Button>
          <Button type="button" onClick={() => void onSubmit()} disabled={isSaving}>
            {t?.save || 'حفظ'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
