'use client';

import { useMemo, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { format } from 'date-fns';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Loader2 } from 'lucide-react';

import { type Currency, type PurchaseOrder, type SupplierPayment } from '@/lib/types';
import { handleUpdateSupplierPaymentFull } from '@/lib/actions';
import { useToast } from '@/hooks/use-toast';
import { formatCurrency } from '@/lib/currency-formatter';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';

type AllocationItem = {
  purchaseOrderId: string;
  amount: number;
};

const editSchema = z.object({
  amount: z.coerce.number().positive(),
  currencyCode: z.string().min(1),
  exchangeRate: z.coerce.number().positive(),
  isAdvance: z.boolean().optional(),
  postingStatus: z.enum(['draft', 'saved', 'posted']).optional().default('posted'),
  reference: z.string().optional(),
  notes: z.string().optional(),
  rateDate: z.string().optional(),
});

type Props = {
  payment: SupplierPayment;
  purchaseOrders: PurchaseOrder[];
  currencies: Currency[];
  defaultCurrencyCode: string;
  t: any;
  tGlobal: any;
  currencySymbol?: string;
};

export function SupplierPaymentEditForm({
  payment,
  purchaseOrders,
  currencies,
  defaultCurrencyCode,
  t,
  tGlobal,
  currencySymbol = '$',
}: Props) {
  const router = useRouter();
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();
  const { lockStatus } = useDocumentLock('supplier-payment', payment.id);
  const isEditLocked = lockStatus.isLocked;
  const exchangeRateLabel = `${t?.exchangeRateShort ?? 'سعر الصرف'} (${t?.against ?? 'مقابل'} ${defaultCurrencyCode})`;
  const [editAllocations, setEditAllocations] = useState<AllocationItem[]>(
    (Array.isArray(payment.allocations) ? payment.allocations : []).map((entry) => ({
      purchaseOrderId: entry.purchaseOrderId,
      amount: Number(entry.amount || 0),
    }))
  );

  const form = useForm<z.infer<typeof editSchema>>({
    resolver: zodResolver(editSchema),
    defaultValues: {
      amount: Number(payment.amount || 0),
      currencyCode: payment.currencyCode || defaultCurrencyCode,
      exchangeRate: Number(payment.exchangeRate || 1),
      isAdvance: payment.isAdvance === true,
      postingStatus: (payment.postingStatus || 'posted') as 'draft' | 'saved' | 'posted',
      reference: payment.reference || '',
      notes: payment.notes || '',
      rateDate: payment.rateDate ? format(new Date(payment.rateDate), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd'),
    },
  });

  const editCurrencyCode = useWatch({ control: form.control, name: 'currencyCode' });
  const editIsAdvance = useWatch({ control: form.control, name: 'isAdvance' });

  const editableOrders = useMemo(() => {
    return purchaseOrders.filter((po) => po.supplierId === payment.supplierId && po.status !== 'cancelled');
  }, [payment.supplierId, purchaseOrders]);

  const handleEditAllocationChange = (purchaseOrderId: string, amount: number) => {
    setEditAllocations((prev) => {
      const filtered = prev.filter((entry) => entry.purchaseOrderId !== purchaseOrderId);
      if (!Number.isFinite(amount) || amount <= 0) return filtered;
      return [...filtered, { purchaseOrderId, amount }];
    });
  };

  const onSubmit = (values: z.infer<typeof editSchema>) => {
    if (isEditLocked) {
      return;
    }

    startTransition(async () => {
      const result = await handleUpdateSupplierPaymentFull({
        paymentId: payment.id,
        amount: Number(values.amount || 0),
        currencyCode: values.currencyCode || defaultCurrencyCode,
        exchangeRate: Number(values.exchangeRate || 1),
        isAdvance: values.isAdvance === true,
        postingStatus: values.postingStatus || 'posted',
        reference: values.reference,
        notes: values.notes,
        rateDate: values.rateDate,
        allocations: editAllocations.filter((entry) => Number(entry.amount || 0) > 0.0001),
      });

      if (result?.success) {
        toast({ title: t?.updateSuccessTitle ?? 'تم تحديث السند بنجاح' });
        router.push('/admin/purchases/payment');
        router.refresh();
      } else {
        toast({
          title: tGlobal?.error ?? 'خطأ',
          description: result?.error || (t?.paymentError ?? 'تعذر تحديث السند'),
          variant: 'destructive',
        });
      }
    });
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t?.edit ?? 'تعديل'} - {payment.id}</CardTitle>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <DocumentLockBanner lockStatus={lockStatus} />

            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <FormField
                control={form.control}
                name="amount"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.amount ?? 'المبلغ'}</FormLabel>
                    <FormControl><Input type="number" step="0.01" min="0" {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="currencyCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.currency ?? 'العملة'}</FormLabel>
                    <Select value={field.value} onValueChange={field.onChange}>
                      <FormControl>
                        <SelectTrigger><SelectValue /></SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {currencies.map((currency) => (
                          <SelectItem key={currency.code} value={currency.code}>{currency.code} - {currency.name}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="exchangeRate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{exchangeRateLabel}</FormLabel>
                    <FormControl><Input type="number" step="0.0001" min="0" {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="rateDate"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.rateDate ?? 'تاريخ السعر'}</FormLabel>
                  <FormControl><Input type="date" {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="postingStatus"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.postingStatus ?? 'مرحلة السند'}</FormLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <FormControl>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="draft">{t?.postingDraft ?? 'مسودة (بدون أثر)'}</SelectItem>
                      <SelectItem value="saved">{t?.postingSaved ?? 'محفوظ (أثر تشغيلي فقط)'}</SelectItem>
                      <SelectItem value="posted">{t?.postingPosted ?? 'مرحل (أثر تشغيلي ومحاسبي)'}</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="isAdvance"
              render={({ field }) => (
                <FormItem className="flex items-center justify-between rounded-md border px-3 py-2">
                  <FormLabel>{t?.advanceToggle ?? 'دفعة مقدمة'}</FormLabel>
                  <FormControl><Switch checked={field.value} onCheckedChange={field.onChange} /></FormControl>
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="reference"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.reference ?? 'المرجع'}</FormLabel>
                  <FormControl><Input {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="notes"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.notes ?? 'ملاحظات'}</FormLabel>
                  <FormControl><Textarea rows={3} {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="space-y-2 rounded-md border p-3">
              <div className="text-sm font-medium">{t?.allocations ?? 'توزيع الدفعة على الفواتير'}</div>
              {editableOrders.length === 0 ? (
                <div className="text-xs text-muted-foreground">{t?.noOpenInvoices ?? 'لا توجد فواتير متاحة.'}</div>
              ) : (
                <div className="rounded-md border overflow-hidden">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>{t?.invoice ?? 'الفاتورة'}</TableHead>
                        <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                        <TableHead className="text-right">{t?.amountDue ?? 'المتبقي'}</TableHead>
                        <TableHead>{t?.allocation ?? 'التوزيع'}</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {editableOrders.map((order) => {
                        const currentFromThisPayment = Number((payment.allocations || []).find((entry) => entry.purchaseOrderId === order.id)?.amount || 0);
                        const availableForEdit = Number(order.amountDue || 0) + currentFromThisPayment;
                        const currentEditAllocation = Number(editAllocations.find((entry) => entry.purchaseOrderId === order.id)?.amount || 0);
                        return (
                          <TableRow key={order.id}>
                            <TableCell>{order.orderNumber || order.id}</TableCell>
                            <TableCell>{order.currencyCode || defaultCurrencyCode}</TableCell>
                            <TableCell className="text-right">{formatCurrency(availableForEdit, currencySymbol)}</TableCell>
                            <TableCell>
                              <Input
                                type="number"
                                step="0.01"
                                min="0"
                                max={Math.max(0, availableForEdit)}
                                value={currentEditAllocation || ''}
                                onChange={(event) => handleEditAllocationChange(order.id, Number(event.target.value))}
                                disabled={editIsAdvance === true || ((order.currencyCode || defaultCurrencyCode) !== (editCurrencyCode || defaultCurrencyCode))}
                              />
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
              )}
            </div>

            <div className="flex gap-2 justify-end">
              <Button type="button" variant="outline" onClick={() => router.push('/admin/purchases/payment')}>
                {tGlobal?.cancel ?? 'إلغاء'}
              </Button>
              <Button type="submit" disabled={isPending || isEditLocked}>
                {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                {t?.save ?? 'حفظ'}
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  );
}
