'use client';

import { useEffect, useState, useTransition } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { PlusCircle, Trash2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { handleDeleteCategory } from '@/lib/actions';
import CustomerCategoryDialog from '@/components/admin/customer-category-dialog';
import type { CustomerCategory } from '@/lib/types';

type Props = {
  categories: CustomerCategory[];
  t: any;
  tGlobal: any;
};

export default function CustomerCategoriesManager({ categories, t, tGlobal }: Props) {
  const [isPending, startTransition] = useTransition();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [items, setItems] = useState<CustomerCategory[]>(categories || []);
  const { toast } = useToast();

  useEffect(() => {
    setItems(categories || []);
  }, [categories]);

  const onDelete = (id: string) => {
    startTransition(async () => {
      const result = await handleDeleteCategory(id);
      if ('error' in result && result.error) {
        toast({ title: t?.saveErrorTitle || 'خطأ', description: result.error, variant: 'destructive' });
        return;
      }
      setItems((prev) => prev.filter((entry) => entry.id !== id));
      toast({ title: t?.saveSuccessTitle || 'تم الحفظ', description: t?.deleteSuccess || 'تم الحذف بنجاح.' });
    });
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center">
        <div className="grid gap-2">
          <CardTitle>{t?.manageCategories || 'إدارة التصنيفات'}</CardTitle>
          <CardDescription>{t?.manageCategoriesDescription || 'إضافة وحذف تصنيفات الزبائن.'}</CardDescription>
        </div>
        <div className="ms-auto">
          <Button size="sm" className="gap-1" onClick={() => setDialogOpen(true)}>
            <PlusCircle className="h-3.5 w-3.5" />
            <span>{t?.addCategory || 'إضافة تصنيف'}</span>
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <div className="border rounded-lg overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t?.reference || 'المرجع'}</TableHead>
                <TableHead>{t?.name || tGlobal?.name || 'الاسم'}</TableHead>
                <TableHead>{t?.englishName || 'الاسم الإنجليزي'}</TableHead>
                <TableHead>{t?.discountPercent || 'الخصم %'}</TableHead>
                <TableHead>{t?.description || 'الوصف'}</TableHead>
                <TableHead className="text-end">{t?.actions || tGlobal?.actions || 'الإجراءات'}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {items.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground py-6">
                    {t?.noItems || 'لا توجد عناصر'}
                  </TableCell>
                </TableRow>
              ) : (
                items.map((category) => (
                  <TableRow key={category.id}>
                    <TableCell className="font-mono text-xs">{category.categoryNumber || '-'}</TableCell>
                    <TableCell>{category.name}</TableCell>
                    <TableCell>{category.nameEn || '-'}</TableCell>
                    <TableCell>{Number(category.discountPercent || 0).toFixed(2)}%</TableCell>
                    <TableCell className="max-w-xs truncate" title={category.description || ''}>{category.description || '-'}</TableCell>
                    <TableCell className="text-end">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-destructive"
                        disabled={isPending}
                        onClick={() => onDelete(category.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>

      <CustomerCategoryDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        t={{ ...tGlobal, ...t }}
        onCategoryCreated={(category) => {
          setItems((prev) => {
            if (prev.some((entry) => entry.id === category.id)) return prev;
            return [...prev, category].sort((left, right) => String(left.name || '').localeCompare(String(right.name || '')));
          });
        }}
      />
    </Card>
  );
}
