'use client';

import { useState, useEffect, useMemo, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { type SalesInvoice, type Customer } from '@/lib/types';
import { handleUpdateInvoice, handleCancelInvoice, checkCancelInvoicePermission } from '@/lib/actions';
import { toast } from '@/hooks/use-toast';
import { AlertCircle, Trash2, Plus } from 'lucide-react';
import { formatCurrency } from '@/lib/currency-formatter';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';

const saleInvoiceSchema = z.object({
  customerId: z.string().min(1, 'Customer is required'),
  amountPaid: z.number().min(0, 'Amount paid must be non-negative'),
  items: z.array(
    z.object({
      materialId: z.string().min(1, 'Material ID is required'),
      name: z.string().min(1, 'Material name is required'),
      unitPrice: z.number().min(0, 'Price must be non-negative'),
      quantity: z.number().min(1, 'Quantity must be at least 1'),
    })
  ).min(1, 'At least one item is required'),
});

type EditInvoiceFormData = z.infer<typeof saleInvoiceSchema>;

type EditInvoiceDialogProps = {
  invoice: SalesInvoice | null;
  customers: Customer[];
  materials: any[];
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess?: () => void;
  t: any;
  currencySymbol?: string;
};

export default function EditInvoiceDialog({
  invoice,
  customers,
  materials,
  open,
  onOpenChange,
  onSuccess,
  t,
  currencySymbol = '$'
}: EditInvoiceDialogProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [itemSelectQuery, setItemSelectQuery] = useState('');
  const [itemSelectInputResetKey, setItemSelectInputResetKey] = useState(0);
  const itemSelectInputRef = useRef<HTMLInputElement | null>(null);
  const [canCancelInvoice, setCanCancelInvoice] = useState(false);
  const [checkingPermission, setCheckingPermission] = useState(false);
  const { lockStatus } = useDocumentLock('invoice', invoice?.id || '', { enabled: open && !!invoice?.id });
  const isEditLocked = !!invoice && lockStatus.isLocked;

  // Check permission when dialog opens
  useEffect(() => {
    if (open && invoice?.status === 'active') {
      setCheckingPermission(true);
      checkCancelInvoicePermission()
        .then(setCanCancelInvoice)
        .catch(() => setCanCancelInvoice(false))
        .finally(() => setCheckingPermission(false));
    } else {
      setCanCancelInvoice(false);
    }
  }, [open, invoice?.status]);

  const form = useForm<EditInvoiceFormData>({
    resolver: zodResolver(saleInvoiceSchema),
    defaultValues: {
      customerId: '',
      amountPaid: 0,
      items: [],
    },
  });

  // Update form values when invoice changes
  useEffect(() => {
    if (invoice) {
      form.reset({
        customerId: invoice.customerId,
        amountPaid: invoice.amountPaid,
        items: invoice.items.map(item => ({
          materialId: item.materialId,
          name: item.name,
          unitPrice: item.unitPrice,
          quantity: item.quantity,
        })),
      });
    }
  }, [invoice, form]);


  const items = form.watch('items');
  const amountPaid = form.watch('amountPaid');
  const subTotal = items.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0);
  const amountDue = subTotal - amountPaid;

  const normalizeSearchText = (value: string) => {
    return value
      .toLowerCase()
      .replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, '')
      .replace(/[إأآٱ]/g, 'ا')
      .replace(/ى/g, 'ي')
      .replace(/ؤ/g, 'و')
      .replace(/ئ/g, 'ي')
      .replace(/ة/g, 'ه')
      .replace(/[^\p{L}\p{N}]+/gu, '');
  };

  const matchesMaterialSearch = (material: any, query: string) => {
    const trimmed = query.trim();
    if (!trimmed) return true;

    const tokens = trimmed
      .split(/\s+/)
      .map((part) => normalizeSearchText(part))
      .filter(Boolean);

    if (tokens.length === 0) return true;

    const normalizedName = normalizeSearchText(material?.name || '');
    const normalizedNumber = normalizeSearchText(String(material?.itemNumber || material?.id || ''));
    const normalizedBarcode = normalizeSearchText(material?.barcode || '');
    const normalizedExtra = (material?.additionalBarcodes || [])
      .map((code: string) => normalizeSearchText(code || ''))
      .join(' ');

    return tokens.every((token) =>
      normalizedName.includes(token) ||
      normalizedNumber.includes(token) ||
      normalizedBarcode.includes(token) ||
      normalizedExtra.includes(token)
    );
  };

  const filteredMaterials = useMemo(
    () => materials.filter((material) => matchesMaterialSearch(material, itemSelectQuery)),
    [materials, itemSelectQuery]
  );

  // Helper function to get item name
  const getItemName = (materialId: string) => {
    const material = materials.find(m => m.id === materialId);
    return material?.name || materialId;
  };

  const addNewItem = () => {
    const currentItems = form.getValues('items');
    form.setValue('items', [
      ...currentItems,
      {
        materialId: materials[0]?.id || '',
        name: materials[0]?.name || '',
        quantity: 1,
        unitPrice: materials[0]?.salePrice || 0,
      }
    ]);
  };

  const removeItem = (index: number) => {
    const currentItems = form.getValues('items');
    if (currentItems.length > 1) {
      form.setValue('items', currentItems.filter((_, i) => i !== index));
    }
  };

  const updateItemMaterial = (index: number, materialId: string) => {
    const material = materials.find(m => m.id === materialId);
    if (material) {
      const currentItems = form.getValues('items');
      currentItems[index] = {
        materialId: material.id,
        name: material.name,
        quantity: currentItems[index].quantity,
        unitPrice: material.salePrice || 0,
      };
      form.setValue('items', currentItems);
    }
  };

  const onSubmit = async (values: EditInvoiceFormData) => {
    if (!invoice || isEditLocked) return;

    setIsLoading(true);
    const result = await handleUpdateInvoice(invoice.id, values);

    if (result.error) {
      toast({
        title: t?.error ?? 'خطأ',
        description: result.error,
        variant: 'destructive',
      });
    } else {
      toast({
        title: t?.saveSuccessTitle ?? 'نجاح',
        description: t?.saveInvoiceSuccess ?? 'تم حفظ الفاتورة بنجاح.',
      });
      onOpenChange(false);
      onSuccess?.();
    }
    setIsLoading(false);
  };

  const onCancel = async () => {
    if (!invoice) return;

    setIsLoading(true);
    const result = await handleCancelInvoice(invoice.id, cancelReason);

    if (result.error) {
      toast({
        title: t?.error ?? 'خطأ',
        description: result.error,
        variant: 'destructive',
      });
    } else {
      toast({
        title: t?.cancelSuccessTitle ?? 'تم الإلغاء',
        description: t?.cancelSuccessDescription ?? 'تم إلغاء الفاتورة بنجاح.',
      });
      setShowCancelConfirm(false);
      onOpenChange(false);
      onSuccess?.();
    }
    setIsLoading(false);
  };

  if (showCancelConfirm) {
    return (
      <Dialog
        open={open}
        onOpenChange={(nextOpen) => {
          if (!nextOpen && typeof document !== 'undefined') {
            (document.activeElement as HTMLElement | null)?.blur();
          }
          onOpenChange(nextOpen);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t?.cancelDialogTitle ?? 'إلغاء الفاتورة'}</DialogTitle>
            <DialogDescription>
              {t?.cancelDialogDescription ?? 'سيتم إلغاء الفاتورة وعكس القيود المحاسبية المرتبطة بها. لا يمكن التراجع عن هذا الإجراء.'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <label htmlFor="cancelReason" className="text-sm font-medium">
                {t?.cancelReasonLabel ?? 'سبب الإلغاء (اختياري)'}
              </label>
              <Textarea
                id="cancelReason"
                value={cancelReason}
                onChange={(e) => setCancelReason(e.target.value)}
                placeholder={t?.cancelReasonPlaceholder ?? 'أدخل سبب إلغاء الفاتورة...'}
                rows={3}
              />
            </div>
          </div>
          <DialogFooter className="flex gap-2">
            <Button
              variant="outline"
              onClick={() => setShowCancelConfirm(false)}
              disabled={isLoading}
            >
              {t?.cancel ?? 'إلغاء'}
            </Button>
            <Button
              variant="destructive"
              onClick={onCancel}
              disabled={isLoading}
            >
              {t?.confirmCancel ?? 'تأكيد الإلغاء'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <Dialog
      open={open}
      onOpenChange={(nextOpen) => {
        if (!nextOpen && typeof document !== 'undefined') {
          (document.activeElement as HTMLElement | null)?.blur();
        }
        onOpenChange(nextOpen);
      }}
    >
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{t?.editDialogTitle ?? 'تعديل الفاتورة'}</DialogTitle>
          <DialogDescription>{invoice?.invoiceNumber}</DialogDescription>
        </DialogHeader>

        {invoice && (
          <>
            <DocumentLockBanner lockStatus={lockStatus} />

            {/* Show cancelled status */}
            {invoice.status === 'cancelled' && (
              <Alert>
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>
                  {t?.invoiceCancelledWarning ?? 'تم إلغاء هذه الفاتورة'}
                  {invoice.cancelledBy && ` ${t?.by ?? 'من قبل'} ${invoice.cancelledBy}`}
                  {invoice.cancelledReason && `: ${invoice.cancelledReason}`}
                </AlertDescription>
              </Alert>
            )}

            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit, () => {
                  toast({
                    title: t?.validationError ?? 'خطأ في التحقق',
                    description: t?.requiredFieldsNote ?? 'يرجى تعبئة الحقول الإلزامية المعلّمة بعلامة *.',
                    variant: 'destructive',
                  });
                })}
                className="space-y-4"
              >
                <p className="text-xs text-muted-foreground">
                  {t?.requiredFieldsNote ?? 'الحقول المشار إليها بعلامة * إلزامية.'}
                </p>
                {/* Customer Selection */}
                <FormField
                  control={form.control}
                  name="customerId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        {t?.selectCustomer ?? 'اختر زبوناً...'}
                        <span className="text-destructive"> *</span>
                      </FormLabel>
                      <Select value={field.value} onValueChange={field.onChange} disabled={invoice.status === 'cancelled'}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder={t?.selectCustomer ?? 'اختر زبوناً...'} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {customers.map((customer) => (
                            <SelectItem key={customer.id} value={customer.id}>
                              {customer.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

              {/* Items Table */}
              <div>
                <div className="flex justify-between items-center mb-2">
                  <FormLabel>
                    {t?.itemsTitle ?? 'بنود الفاتورة'}
                    <span className="text-destructive"> *</span>
                  </FormLabel>
                  {invoice.status === 'active' && (
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={addNewItem}
                      disabled={isLoading}
                    >
                      <Plus className="h-4 w-4 mr-2" />
                      {t?.addItem ?? 'إضافة صنف'}
                    </Button>
                  )}
                </div>
                <Card className="mt-2">
                  <CardContent className="p-0">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>{t?.item ?? 'الصنف'}</TableHead>
                          <TableHead className="text-center">{t?.quantity ?? 'الكمية'}</TableHead>
                          <TableHead className="text-center">{t?.price ?? 'السعر'}</TableHead>
                          <TableHead className="text-center">{t?.total ?? 'الإجمالي'}</TableHead>
                          {invoice.status === 'active' && <TableHead className="text-center">{t?.actions ?? 'إجراءات'}</TableHead>}
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {items.map((item, index) => (
                          <TableRow key={index}>
                            <TableCell>
                              {invoice.status === 'active' ? (
                                <Select
                                  value={item.materialId}
                                  onOpenChange={(nextOpen) => {
                                    if (nextOpen) {
                                      setItemSelectInputResetKey((prev) => prev + 1);
                                    } else {
                                      setItemSelectQuery('');
                                    }
                                  }}
                                  onValueChange={(value) => updateItemMaterial(index, value)}
                                  disabled={isLoading}
                                >
                                  <SelectTrigger className="w-full">
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <div className="p-2">
                                      <Input
                                        key={itemSelectInputResetKey}
                                        ref={itemSelectInputRef}
                                        placeholder={t?.searchItemPlaceholder ?? 'ابحث عن الصنف...'}
                                        defaultValue={itemSelectQuery}
                                        onBlur={(e) => setItemSelectQuery(e.currentTarget.value)}
                                        onKeyDown={(e) => {
                                          if (e.key === 'Enter') {
                                            e.preventDefault();
                                            setItemSelectQuery((e.currentTarget as HTMLInputElement).value);
                                            (e.currentTarget as HTMLInputElement).blur();
                                          }
                                        }}
                                        autoFocus
                                      />
                                    </div>
                                    {filteredMaterials.length === 0 ? (
                                      <SelectItem value="__no_results__" disabled>
                                        {t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.'}
                                      </SelectItem>
                                    ) : (
                                      filteredMaterials.map((material) => (
                                        <SelectItem key={material.id} value={material.id}>
                                          {material.name}
                                        </SelectItem>
                                      ))
                                    )}
                                  </SelectContent>
                                </Select>
                              ) : (
                                <span>{item.name}</span>
                              )}
                            </TableCell>
                            <TableCell className="text-center">
                              {invoice.status === 'active' ? (
                                <Input
                                  type="number"
                                  min="1"
                                  value={item.quantity}
                                  onChange={(e) => {
                                    const newItems = [...items];
                                    newItems[index].quantity = parseInt(e.target.value) || 1;
                                    form.setValue('items', newItems);
                                  }}
                                  className="w-20"
                                  disabled={isLoading}
                                />
                              ) : (
                                item.quantity
                              )}
                            </TableCell>
                            <TableCell className="text-center">
                              {invoice.status === 'active' ? (
                                <Input
                                  type="number"
                                  step="0.01"
                                  value={item.unitPrice}
                                  onChange={(e) => {
                                    const newItems = [...items];
                                    newItems[index].unitPrice = parseFloat(e.target.value) || 0;
                                    form.setValue('items', newItems);
                                  }}
                                  className="w-24"
                                  disabled={isLoading}
                                />
                              ) : (
                                formatCurrency(item.unitPrice, currencySymbol)
                              )}
                            </TableCell>
                            <TableCell className="text-center font-mono">
                              {formatCurrency(item.quantity * item.unitPrice, currencySymbol)}
                            </TableCell>
                            {invoice.status === 'active' && (
                              <TableCell className="text-center">
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => removeItem(index)}
                                  disabled={items.length === 1 || isLoading}
                                >
                                  <Trash2 className="h-4 w-4 text-destructive" />
                                </Button>
                              </TableCell>
                            )}
                          </TableRow>
                        ))}
                      </TableBody>
                      <TableFooter>
                        <TableRow>
                          <TableCell colSpan={invoice.status === 'active' ? 4 : 3} className="text-end font-bold">
                            {t?.subTotal ?? 'المجموع الفرعي'}:
                          </TableCell>
                          <TableCell className="text-center font-bold font-mono">{formatCurrency(subTotal, currencySymbol)}</TableCell>
                          {invoice.status === 'active' && <TableCell></TableCell>}
                        </TableRow>
                      </TableFooter>
                    </Table>
                  </CardContent>
                </Card>
                {form.formState.errors.items && (
                  <p className="text-sm text-destructive mt-2">
                    {t?.itemsRequired ?? 'يجب إضافة صنف واحد على الأقل.'}
                  </p>
                )}
              </div>

              {/* Amount Paid */}
              <FormField
                control={form.control}
                name="amountPaid"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.amountPaid ?? 'المبلغ المدفوع'}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        step="0.01"
                        {...field}
                        onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)}
                        disabled={invoice.status === 'cancelled' || isLoading}
                      />
                    </FormControl>
                    <FormDescription>
                      {t?.amountDue ?? 'المبلغ المتبقي'}: {formatCurrency(amountDue, currencySymbol)}
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Action Buttons */}
              <DialogFooter className="flex gap-2 justify-between">
                <div>
                  {invoice.status === 'active' && canCancelInvoice && (
                    <Button
                      type="button"
                      variant="destructive"
                      onClick={() => setShowCancelConfirm(true)}
                      disabled={isLoading || checkingPermission}
                    >
                      {t?.cancelInvoice ?? 'إلغاء الفاتورة'}
                    </Button>
                  )}
                </div>
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => onOpenChange(false)}
                    disabled={isLoading}
                  >
                    {t?.cancel ?? 'إلغاء'}
                  </Button>
                  {invoice.status === 'active' && (
                    <Button type="submit" disabled={isLoading || isEditLocked}>
                      {t?.saveChangesButton ?? 'حفظ التغييرات'}
                    </Button>
                  )}
                </div>
              </DialogFooter>
            </form>
          </Form>
        </>
        )}
      </DialogContent>
    </Dialog>
  );
}
