"use client";

import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { useToast } from "@/hooks/use-toast";
import { useDocumentLock } from '@/hooks/use-document-lock';
import { PlusCircle, Loader2, MoreHorizontal } from "lucide-react";
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';

import { handleAddItemGroup, handleUpdateItemGroup, handleDeleteItemGroup } from "@/lib/actions";
import type { ItemGroup } from "@/lib/types";

const itemGroupSchema = z.object({
  groupNumber: z.string().optional(),
  name: z.string().min(2, "Name must be at least 2 characters."),
  isPosEnabled: z.coerce.boolean().default(false),
  usesDefaultTax: z.coerce.boolean().optional().default(true),
  taxRate: z.coerce.number().min(0).max(100).optional(),
});

type ItemGroupsManagerProps = {
  groups: ItemGroup[];
  t?: any;
  tGlobal?: any;
};

export default function ItemGroupsManager({ groups, t = {}, tGlobal = {} }: ItemGroupsManagerProps) {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const [isDeletePending, startDeleteTransition] = useTransition();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingGroup, setEditingGroup] = useState<ItemGroup | null>(null);
  const { lockStatus } = useDocumentLock('item-group', editingGroup?.id || '', { enabled: dialogOpen && !!editingGroup?.id });
  const isEditLocked = dialogOpen && !!editingGroup && lockStatus.isLocked;

  const form = useForm<z.infer<typeof itemGroupSchema>>({
    resolver: zodResolver(itemGroupSchema),
    defaultValues: {
      groupNumber: "",
      name: "",
      isPosEnabled: false,
    },
  });

  const suggestNextGroupNumber = () => {
    const next = groups.reduce((max, group) => {
      const parsed = parseInt(String(group?.groupNumber || '').replace(/\D+/g, ''), 10);
      return Number.isFinite(parsed) ? Math.max(max, parsed) : max;
    }, 0) + 1;
    return String(next);
  };

  const openAddDialog = () => {
    setEditingGroup(null);
    form.reset({ groupNumber: suggestNextGroupNumber(), name: "", isPosEnabled: false, usesDefaultTax: true, taxRate: undefined });
    setDialogOpen(true);
  };

  const openEditDialog = (group: ItemGroup) => {
    setEditingGroup(group);
    form.reset({ 
      groupNumber: String(group.groupNumber || ''),
      name: group.name, 
      isPosEnabled: !!group.isPosEnabled,
      usesDefaultTax: group.usesDefaultTax ?? true,
      taxRate: group.taxRate !== undefined ? group.taxRate : undefined,
    });
    setDialogOpen(true);
  };

  const onSubmit = (values: z.infer<typeof itemGroupSchema>) => {
    if (isEditLocked) return;

    startTransition(async () => {
      // Normalize tax data before sending to server
      const normalizedValues: any = {
        name: values.name,
        isPosEnabled: values.isPosEnabled,
        usesDefaultTax: values.usesDefaultTax ?? true,
      };
      
      // Only include taxRate if NOT using default and taxRate is provided
      if (values.usesDefaultTax === false && values.taxRate !== undefined) {
        normalizedValues.taxRate = Number(values.taxRate);
      }

      const result = editingGroup
        ? await handleUpdateItemGroup(editingGroup.id, normalizedValues)
        : await handleAddItemGroup(normalizedValues);

      if (result.success) {
        toast({ title: t?.saveSuccessTitle ?? "تم الحفظ بنجاح" });
        setDialogOpen(false);
        setEditingGroup(null);
      } else {
        toast({ title: t?.saveErrorTitle ?? "تعذر الحفظ", description: result.error, variant: "destructive" });
      }
    });
  };

  const onDelete = (id: string) => {
    startDeleteTransition(async () => {
      const result = await handleDeleteItemGroup(id);
      if (result.success) {
        toast({ title: t?.deleteSuccessTitle ?? "تم الحذف بنجاح" });
      } else {
        toast({ title: t?.deleteErrorTitle ?? "تعذر الحذف", description: result.error, variant: "destructive" });
      }
    });
  };

  return (
    <>
      <Card>
        <CardHeader className="flex flex-row items-center">
          <div className="grid gap-2">
            <CardTitle>{t?.manageItemGroups ?? "إدارة مجموعات الأصناف"}</CardTitle>
            <CardDescription>{t?.manageItemGroupsDescription ?? "إضافة وتعديل مجموعات الأصناف وتفعيلها في نقطة البيع."}</CardDescription>
          </div>
          <div className="ml-auto flex items-center gap-2">
            <Button size="sm" className="gap-1" onClick={openAddDialog}>
              <PlusCircle className="h-3.5 w-3.5" />
              <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">{t?.addButton ?? "إضافة"}</span>
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t?.groupNumberLabel ?? "الرقم"}</TableHead>
                <TableHead>{t?.itemGroupNameLabel ?? "اسم المجموعة"}</TableHead>
                <TableHead>{t?.posEnabledLabel ?? "مفعلة في نقطة البيع"}</TableHead>
                <TableHead className="text-right">{tGlobal?.actions ?? "الإجراءات"}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {groups.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={4} className="h-24 text-center text-muted-foreground">
                    {t?.noItemsFound ?? "لا توجد عناصر"}
                  </TableCell>
                </TableRow>
              ) : (
                groups.map((group) => (
                  <TableRow key={group.id}>
                    <TableCell className="font-mono text-xs">{group.groupNumber || '-'}</TableCell>
                    <TableCell className="font-medium">{group.name}</TableCell>
                    <TableCell>{group.isPosEnabled ? t?.yesLabel ?? "نعم" : t?.noLabel ?? "لا"}</TableCell>
                    <TableCell className="text-right">
                      <AlertDialog>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button aria-haspopup="true" size="icon" variant="ghost" disabled={isDeletePending}>
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem onSelect={() => openEditDialog(group)}>
                              {tGlobal?.edit ?? "تعديل"}
                            </DropdownMenuItem>
                            <AlertDialogTrigger asChild>
                              <DropdownMenuItem className="text-red-600" onSelect={(e) => e.preventDefault()}>
                                {tGlobal?.delete ?? "حذف"}
                              </DropdownMenuItem>
                            </AlertDialogTrigger>
                          </DropdownMenuContent>
                        </DropdownMenu>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>{t?.deleteDialogTitle ?? "تأكيد الحذف"}</AlertDialogTitle>
                            <AlertDialogDescription>
                              {(t?.deleteDialogDescription ?? "هل أنت متأكد من حذف المجموعة: {name}؟").replace("{name}", group.name)}
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>{tGlobal?.cancel ?? "إلغاء"}</AlertDialogCancel>
                            <AlertDialogAction onClick={() => onDelete(group.id)} className="bg-destructive hover:bg-destructive/90">
                              {isDeletePending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : (tGlobal?.delete ?? "حذف")}
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog
        open={dialogOpen}
        onOpenChange={(open) => {
          if (!open && typeof document !== 'undefined') {
            (document.activeElement as HTMLElement | null)?.blur();
          }
          setDialogOpen(open);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingGroup ? (t?.editDialogTitle ?? "تعديل المجموعة") : (t?.addDialogTitle ?? "إضافة مجموعة")}</DialogTitle>
            <DialogDescription>
              {editingGroup ? (t?.editDialogDescription ?? "قم بتحديث بيانات المجموعة.") : (t?.addDialogDescription ?? "أدخل بيانات المجموعة الجديدة.")}
            </DialogDescription>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              {editingGroup && <DocumentLockBanner lockStatus={lockStatus} />}
              <p className="text-xs text-muted-foreground">
                {t?.requiredFieldsNote ?? 'الحقول المشار إليها بعلامة * إلزامية.'}
              </p>
              <FormField
                control={form.control}
                name="groupNumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.groupNumberLabel ?? "الرقم التسلسلي"}</FormLabel>
                    <FormControl>
                      <Input {...field} readOnly disabled />
                    </FormControl>
                    {!editingGroup && (
                      <p className="text-xs text-muted-foreground">
                        {t?.groupNumberHint ?? 'يتم توليد الرقم النهائي تلقائياً عند الحفظ مع منع التضارب بين المستخدمين.'}
                      </p>
                    )}
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t?.itemGroupNameLabel ?? "اسم المجموعة"}
                      <span className="text-destructive"> *</span>
                    </FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="isPosEnabled"
                render={({ field }) => (
                  <FormItem className="flex items-center gap-2">
                    <FormControl>
                      <Checkbox checked={!!field.value} onCheckedChange={field.onChange} />
                    </FormControl>
                    <FormLabel className="mb-0">{t?.posEnabledLabel ?? "مفعلة في نقطة البيع"}</FormLabel>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <p className="text-sm font-medium">
                {t?.lineLevelTaxLabel ?? "ضريبة على كل سطر"}
              </p>
              {form.watch('usesDefaultTax') === false && (
                <FormField
                  control={form.control}
                  name="taxRate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.itemTaxRateLabel ?? "نسبة الضريبة الخاصة بالمجموعة (%)"}</FormLabel>
                      <FormControl>
                        <Input 
                          {...field}
                          value={field.value ?? ''}
                          type="number" 
                          placeholder="0" 
                          step="0.01"
                          min="0"
                          max="100"
                        />
                      </FormControl>
                      <p className="text-xs text-muted-foreground mt-1">
                        {t?.itemTaxRateHelp ?? "أدخل نسبة الضريبة لهذه المجموعة (0-100). ستتفوق على الضريبة الافتراضية."}
                      </p>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}
              <FormField
                control={form.control}
                name="usesDefaultTax"
                render={({ field }) => (
                  <FormItem className="flex items-center gap-2">
                    <FormControl>
                      <Checkbox checked={!!field.value} onCheckedChange={field.onChange} />
                    </FormControl>
                    <FormLabel className="mb-0">{t?.useDefaultTaxLabel ?? "استخدام الضريبة الافتراضية"}</FormLabel>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>
                  {tGlobal?.cancel ?? "إلغاء"}
                </Button>
                <Button type="submit" disabled={isPending || isEditLocked}>
                  {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                  {tGlobal?.save ?? "حفظ"}
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>
    </>
  );
}
