'use client';

import { useEffect, useMemo, useState, useTransition } from 'react';
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, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Loader2, Check, ChevronsUpDown } from 'lucide-react';
import { Plus } from 'lucide-react';
import { type Customer, type Supplier, type Bank, type Currency } from '@/lib/types';
import { useToast } from '@/hooks/use-toast';
import { handleCustomerPayment } from '@/lib/actions';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { cn } from '@/lib/utils';
import { AddBankDialog } from './add-bank-dialog';
import { AddCurrencyDialog } from './add-currency-dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { X } from 'lucide-react';
import { formatCurrency } from '@/lib/currency-formatter';

type CheckItem = {
  id: string;
  checkNumber: string;
  bankId: string;
  bankName: string;
  checkDate: string;
  currency: string;
  amount: number;
};

const checkFormSchema = z.object({
  checkNumber: z.string().min(1, 'Check number is required'),
  bankId: z.string().min(1, 'Bank is required'),
  checkDate: z.string().min(1, 'Check date is required'),
  currency: z.string().min(1, 'Currency is required'),
  amount: z.coerce.number().min(0.01, 'Amount must be greater than 0'),
});

const paymentVoucherSchema = z.object({
  customerId: z.string().min(1, 'Please select a customer or supplier.'),
  amount: z.coerce.number().min(0.01, 'Amount must be greater than 0.'),
  paymentMethod: z.enum(['cash', 'check', 'bank_transfer', 'credit']),
});

type Party = {
  id: string;
  name: string;
  type: 'customer' | 'supplier';
  originalId: string;
  balance: number;
};

type PaymentVoucherFormProps = {
  customers: Customer[];
  suppliers: Supplier[];
  banks: Bank[];
  currencies: Currency[];
  defaultCurrency: Currency | null;
  initialCustomerId?: string;
  t: any;
  tGlobal: any;
  currencySymbol?: string;
};

export default function PaymentVoucherForm({ 
  customers,
  suppliers,
  banks,
  currencies,
  defaultCurrency,
  initialCustomerId,
  t, 
  tGlobal,
  currencySymbol = '$'
}: PaymentVoucherFormProps) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const [selectedPartyId, setSelectedPartyId] = useState<string>('');
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [bankOptions, setBankOptions] = useState<Bank[]>(banks);
  const [currencyOptions, setCurrencyOptions] = useState<Currency[]>(currencies);
  const [checks, setChecks] = useState<CheckItem[]>([]);
  const [showCheckForm, setShowCheckForm] = useState(false);
  const [isAddBankDialogOpen, setIsAddBankDialogOpen] = useState(false);

  const form = useForm<z.infer<typeof paymentVoucherSchema>>({
    resolver: zodResolver(paymentVoucherSchema),
    defaultValues: {
      customerId: '',
      amount: 0,
      paymentMethod: 'cash',
    },
  });

  const checkForm = useForm<z.infer<typeof checkFormSchema>>({
    resolver: zodResolver(checkFormSchema),
    defaultValues: {
      checkNumber: '',
      bankId: '',
      checkDate: new Date().toISOString().split('T')[0],
      currency: defaultCurrency?.code || 'USD',
      amount: 0,
    }
  });

  const parties = useMemo<Party[]>(() => {
    const customerParties: Party[] = customers.map(c => ({
      id: `customer:${c.id}`,
      name: c.name,
      type: 'customer' as const,
      originalId: c.id,
      balance: c.balance
    }));
    const supplierParties: Party[] = suppliers.map(s => ({
      id: `supplier:${s.id}`,
      name: s.name,
      type: 'supplier' as const,
      originalId: s.id,
      balance: s.balance
    }));
    return [...customerParties, ...supplierParties];
  }, [customers, suppliers]);

  const filteredParties = useMemo(() => {
    if (!searchTerm) return parties;
    return parties.filter(p => p.name.toLowerCase().includes(searchTerm.toLowerCase()));
  }, [parties, searchTerm]);

  useEffect(() => {
    if (!initialCustomerId) return;
    const partyId = `customer:${initialCustomerId}`;
    const exists = parties.some((party) => party.id === partyId);
    if (!exists) return;
    if (selectedPartyId === partyId) return;
    setSelectedPartyId(partyId);
    form.setValue('customerId', initialCustomerId);
  }, [initialCustomerId, parties, selectedPartyId, form]);

  const selectedParty = useMemo(() => {
    return parties.find(p => p.id === selectedPartyId);
  }, [selectedPartyId, parties]);

  const selectedCustomer = useMemo(() => {
    if (!selectedParty || selectedParty.type !== 'customer') return undefined;
    return customers.find(c => c.id === selectedParty.originalId);
  }, [selectedParty, customers]);

  const onSubmit = (values: z.infer<typeof paymentVoucherSchema>) => {
    // Validate checks when payment method is check
    if (values.paymentMethod === 'check') {
      if (checks.length === 0) {
        toast({
          title: tGlobal?.error,
          description: t?.addAtLeastOneCheck ?? 'يجب إضافة شيك واحد على الأقل',
          variant: 'destructive',
        });
        return;
      }
    }

    startTransition(async () => {
      const result = await handleCustomerPayment({ ...values, checks });
      if (result.success) {
        toast({ title: t?.paymentSuccessTitle ?? 'تم تسجيل الدفعة بنجاح.', description: '' });
        form.reset({
          customerId: '',
          amount: 0,
          paymentMethod: 'cash',
        });
        checkForm.reset();
        setSelectedPartyId('');
      } else {
        toast({ title: t?.paymentErrorTitle ?? 'فشل تسجيل الدفعة.', description: result.error, variant: 'destructive' });
      }
    });
  };

  const handleAddCheck = (formValues: z.infer<typeof checkFormSchema>) => {
    const bank = bankOptions.find((b) => b.id === formValues.bankId);
    const newCheck: CheckItem = {
      id: Math.random().toString(36).substr(2, 9),
      checkNumber: formValues.checkNumber,
      bankId: formValues.bankId,
      bankName: bank?.name || '',
      checkDate: formValues.checkDate,
      currency: formValues.currency,
      amount: Number(formValues.amount || 0),
    };
    setChecks([...checks, newCheck]);
    checkForm.reset({
      checkNumber: '',
      bankId: '',
      checkDate: format(new Date(), 'yyyy-MM-dd'),
      currency: defaultCurrency?.code || 'JOD',
      amount: 0,
    });
    setShowCheckForm(false);
    toast({
      title: t?.checkAddedTitle ?? 'تم إضافة الشيك',
      description: `${t?.checkNumber ?? 'رقم الشيك'}: ${formValues.checkNumber}`,
    });
  };

  const handleRemoveCheck = (id: string) => {
    setChecks(checks.filter((check) => check.id !== id));
  };

  return (
    <Card className="w-full max-w-5xl mx-auto">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)}>
          <CardHeader>
            <CardTitle>{t?.paymentVoucherTitle ?? 'سند قبض'}</CardTitle>
            <CardDescription>{t?.paymentVoucherDescription ?? 'تسجيل دفعة من رصيد زبون.'}</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-4">
              <FormField
                control={form.control}
                name="customerId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.selectParty ?? 'اختر زبوناً أو مورداً...'}</FormLabel>
                     <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
                        <PopoverTrigger asChild>
                            <FormControl>
                                <Button
                                    variant="outline"
                                    role="combobox"
                                    className={cn("w-full justify-between", !selectedPartyId && "text-muted-foreground")}
                                >
                                    {selectedParty
                                        ? `${selectedParty.name} (${selectedParty.type === 'customer' ? t?.customerLabel ?? 'زبون' : t?.supplierLabel ?? 'مورد'})`
                                        : (t?.selectParty ?? 'اختر زبوناً أو مورداً...')}
                                    <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
                                </Button>
                            </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-[--radix-popover-trigger-width] p-0">
                            <div className="p-2">
                                <Input
                                    placeholder={t?.searchParty ?? "ابحث عن زبون أو مورد..."}
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    autoFocus
                                />
                            </div>
                            <div className="max-h-60 overflow-y-auto">
                                {filteredParties.map((party) => (
                                    <div
                                        key={party.id}
                                        onClick={() => {
                                            if (party.type === 'customer') {
                                              field.onChange(party.originalId);
                                            }
                                            setSelectedPartyId(party.id);
                                            setPopoverOpen(false);
                                            setSearchTerm('');
                                        }}
                                        className={cn(
                                            "relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent hover:bg-accent",
                                        )}
                                        data-selected={party.id === selectedPartyId}
                                    >
                                        <Check
                                            className={cn(
                                                "me-2 h-4 w-4",
                                                party.id === selectedPartyId ? "opacity-100" : "opacity-0"
                                            )}
                                        />
                                        <span className="flex-1">{party.name}</span>
                                        <span className="text-xs text-muted-foreground">
                                          ({party.type === 'customer' ? t?.customerLabel ?? 'زبون' : t?.supplierLabel ?? 'مورد'})
                                        </span>
                                    </div>
                                ))}
                            </div>
                        </PopoverContent>
                    </Popover>
                    <FormMessage />
                  </FormItem>
                )}
              />
              {selectedParty && (
                <FormItem>
                    <FormLabel>{t?.partyBalance ?? 'الرصيد الحالي'}</FormLabel>
                    <Input value={formatCurrency(selectedParty.balance, currencySymbol)} readOnly disabled className="font-bold text-lg"/>
                </FormItem>
              )}
               <FormField
                control={form.control}
                name="amount"
                render={({ field }) => (
                    <FormItem>
                        <FormLabel>{t?.paymentAmountLabel ?? 'قيمة الدفعة'}</FormLabel>
                        <FormControl><Input type="number" {...field} step="0.01" onFocus={(e) => e.target.select()} /></FormControl>
                        <FormMessage />
                    </FormItem>
                )}
                />

              {/* Payment Method */}
              <FormField
                control={form.control}
                name="paymentMethod"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t?.paymentMethod ?? 'طريقة الدفع'}</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="cash">{t?.cash ?? 'نقداً'}</SelectItem>
                        <SelectItem value="check">{t?.check ?? 'شيك'}</SelectItem>
                        <SelectItem value="bank_transfer">{t?.bankTransfer ?? 'تحويل بنكي'}</SelectItem>
                        <SelectItem value="credit">{t?.credit ?? 'حساب دائن'}</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Check Details Section - Show when payment method is 'check' */}
            {form.watch('paymentMethod') === 'check' && (
              <Card className="border">
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm">{t?.checkDetails ?? 'تفاصيل الشيك'}</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Checks Table */}
                  {checks.length > 0 && (
                    <div className="border rounded-lg overflow-hidden">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>{t?.checkNumber ?? 'رقم الشيك'}</TableHead>
                            <TableHead>{t?.bankName ?? 'اسم البنك'}</TableHead>
                            <TableHead>{t?.checkDate ?? 'التاريخ'}</TableHead>
                            <TableHead className="text-right">{t?.amount ?? 'المبلغ'}</TableHead>
                            <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                            <TableHead className="w-10 text-center">{t?.actions ?? 'إجراءات'}</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {checks.map((check) => (
                            <TableRow key={check.id}>
                              <TableCell className="font-medium">{check.checkNumber}</TableCell>
                              <TableCell>{check.bankName}</TableCell>
                              <TableCell>{format(new Date(check.checkDate), 'dd/MM/yyyy')}</TableCell>
                              <TableCell className="text-right">{formatCurrency(check.amount || 0, currencySymbol)}</TableCell>
                              <TableCell>{check.currency}</TableCell>
                              <TableCell className="text-center">
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="icon"
                                  onClick={() => handleRemoveCheck(check.id)}
                                  className="h-8 w-8"
                                >
                                  <X className="h-4 w-4" />
                                </Button>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  )}

                  {/* Add Check Form */}
                  {!showCheckForm && (
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setShowCheckForm(true)}
                      className="w-full"
                    >
                      {t?.addCheck ?? '+ إضافة شيك'}
                    </Button>
                  )}

                  {showCheckForm && (
                    <div className="border rounded-lg overflow-hidden">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>{t?.checkNumber ?? 'رقم الشيك'} *</TableHead>
                            <TableHead>{t?.bankName ?? 'اسم البنك'} *</TableHead>
                            <TableHead>{t?.checkDate ?? 'تاريخ الشيك'} *</TableHead>
                            <TableHead>{t?.amount ?? 'المبلغ'} *</TableHead>
                            <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                            <TableHead className="w-24 text-center">{t?.actions ?? 'إجراءات'}</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          <TableRow>
                            <Form {...checkForm}>
                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="checkNumber"
                                  render={({ field }) => (
                                    <FormItem>
                                      <FormControl>
                                        <Input
                                          placeholder={t?.checkNumberPlaceholder ?? 'مثال: CHK-001234'}
                                          {...field}
                                          className="h-8"
                                        />
                                      </FormControl>
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  )}
                                />
                              </TableCell>

                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="bankId"
                                  render={({ field }) => (
                                    <FormItem>
                                      <div className="flex items-center gap-2">
                                        <Select
                                          onValueChange={(bankId) => {
                                            if (bankId === '__add_bank__') {
                                              setIsAddBankDialogOpen(true);
                                              return;
                                            }
                                            field.onChange(bankId);
                                            const selectedBank = bankOptions.find((bank) => bank.id === bankId);
                                            if (selectedBank?.currencyCode) {
                                              checkForm.setValue('currency', selectedBank.currencyCode, { shouldValidate: true });
                                            }
                                          }}
                                          defaultValue={field.value}
                                        >
                                          <FormControl>
                                            <SelectTrigger className="h-8 w-full">
                                              <SelectValue placeholder={t?.selectBank ?? 'اختر بنك'} />
                                            </SelectTrigger>
                                          </FormControl>
                                          <SelectContent>
                                            {bankOptions.map((bank) => (
                                              <SelectItem key={bank.id} value={bank.id}>
                                                {bank.fullName || bank.name} {bank.branch ? `- ${bank.branch}` : ''}
                                              </SelectItem>
                                            ))}
                                            <Separator className="my-1" />
                                            <SelectItem value="__add_bank__" className="flex items-center justify-center gap-2 py-2 text-center text-xs font-medium text-blue-600 hover:text-blue-700">
                                              <Plus className="h-3 w-3" />
                                              {t?.addBank || 'إضافة بنك'}
                                            </SelectItem>
                                          </SelectContent>
                                        </Select>
                                      </div>
                                      <AddBankDialog
                                        isOpen={isAddBankDialogOpen}
                                        onOpenChange={setIsAddBankDialogOpen}
                                        currencies={currencyOptions}
                                        accountOptions={[]}
                                        t={t}
                                        tGlobal={tGlobal}
                                        onBankAdded={(newBank) => {
                                          setBankOptions((prev) => [...prev, newBank]);
                                          checkForm.setValue('bankId', newBank.id, { shouldValidate: true });
                                          if (newBank.currencyCode) {
                                            checkForm.setValue('currency', newBank.currencyCode, { shouldValidate: true });
                                          }
                                        }}
                                      />
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  )}
                                />
                              </TableCell>

                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="checkDate"
                                  render={({ field }) => (
                                    <FormItem>
                                      <FormControl>
                                        <Input
                                          type="date"
                                          {...field}
                                          className="h-8"
                                        />
                                      </FormControl>
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  )}
                                />
                              </TableCell>

                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="amount"
                                  render={({ field }) => (
                                    <FormItem>
                                      <FormControl>
                                        <Input type="number" step="0.01" min="0" {...field} className="h-8" />
                                      </FormControl>
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  )}
                                />
                              </TableCell>

                              <TableCell>
                                <FormField
                                  control={checkForm.control}
                                  name="currency"
                                  render={({ field }) => {
                                    const selectedCurrency = currencyOptions.find(c => c.code === field.value);
                                    return (
                                    <FormItem>
                                      <Select onValueChange={field.onChange} value={field.value}>
                                        <FormControl>
                                          <SelectTrigger className="h-8 w-full">
                                            <SelectValue>
                                              {selectedCurrency ? `${selectedCurrency.code} - ${selectedCurrency.symbol}` : t?.currency ?? 'العملة'}
                                            </SelectValue>
                                          </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                          {currencyOptions.map((currency) => (
                                            <SelectItem key={currency.code} value={currency.code}>
                                              {currency.code} - {currency.name} ({currency.symbol})
                                            </SelectItem>
                                          ))}
                                        </SelectContent>
                                      </Select>
                                      <FormMessage className="text-xs" />
                                    </FormItem>
                                  );
                                  }}
                                />
                              </TableCell>

                              <TableCell className="text-center">
                                <div className="flex gap-1 justify-center">
                                  <Button
                                    type="button"
                                    size="icon"
                                    onClick={() => checkForm.handleSubmit(handleAddCheck)()}
                                    className="h-8 w-8"
                                    title={t?.addCheck ?? 'إضافة شيك'}
                                  >
                                    <Plus className="h-4 w-4" />
                                  </Button>
                                  <Button
                                    type="button"
                                    variant="outline"
                                    size="icon"
                                    onClick={() => setShowCheckForm(false)}
                                    className="h-8 w-8"
                                    title={tGlobal?.cancel ?? 'إلغاء'}
                                  >
                                    <X className="h-4 w-4" />
                                  </Button>
                                </div>
                              </TableCell>
                            </Form>
                          </TableRow>
                        </TableBody>
                      </Table>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}
          </CardContent>
          <CardFooter>
             <Button type="submit" disabled={isPending || !selectedPartyId} className="w-full">
                {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {t?.savePaymentButton ?? 'حفظ الدفعة'}
            </Button>
          </CardFooter>
        </form>
      </Form>
    </Card>
  );
}

