'use client';

import { useEffect, useState } from 'react';
import * as z from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Plus } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import type { Bank, Currency } from '@/lib/types';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import AccountCodeSelector, { type AccountCodeOption } from '@/components/admin/account-code-selector';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { AddCurrencyDialog } from '@/components/admin/add-currency-dialog';

const bankSchema = z.object({
  bankNumber: z.string().max(30).optional(),
  bankCode: z.string().trim().min(2, 'Bank code is required').max(30).regex(/^[A-Za-z0-9_-]+$/, 'Bank code contains invalid characters'),
  fullName: z.string().min(1, 'Full bank name is required'),
  branch: z.string().optional(),
  iban: z.string().trim().max(34).optional().or(z.literal('')),
  swiftCode: z.string().trim().max(16).regex(/^[A-Za-z0-9]*$/, 'SWIFT must contain only letters and numbers').optional().or(z.literal('')),
  accountNumber: z.string().max(64).optional(),
  contactName: z.string().max(120).optional(),
  contactPhone: z.string().max(40).optional(),
  notes: z.string().max(1000).optional(),
  isActive: z.coerce.boolean().optional().default(true),
  accountCode: z.string().optional(),
  currencyCode: z.string().min(1, 'Currency is required'),
});

type BankFormValues = z.infer<typeof bankSchema>;

interface AddBankDialogProps {
  onBankAdded: (bank: Bank) => void;
  currencies: Currency[];
  accountOptions: AccountCodeOption[];
  t: any;
  tGlobal: any;
  isOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
}

export function AddBankDialog({ onBankAdded, currencies, accountOptions, t, tGlobal, isOpen: externalIsOpen, onOpenChange: externalOnOpenChange }: AddBankDialogProps) {
  const [internalOpen, setInternalOpen] = useState(false);
  const open = externalIsOpen ?? internalOpen;
  const setOpen = (nextOpen: boolean) => {
    if (!nextOpen) {
      setBankCodeEditedManually(false);
      setAccountCodeEditedManually(false);
    }
    (externalOnOpenChange ?? setInternalOpen)(nextOpen);
  };
  const [isLoading, setIsLoading] = useState(false);
  const [bankCodeEditedManually, setBankCodeEditedManually] = useState(false);
  const [accountCodeEditedManually, setAccountCodeEditedManually] = useState(false);
  const [runtimeCurrencies, setRuntimeCurrencies] = useState<Currency[]>(currencies || []);
  const { toast } = useToast();

  const generateBankCode = (sourceName: string) => {
    const raw = String(sourceName || '')
      .trim()
      .toUpperCase()
      .replace(/\s+/g, '-')
      .replace(/[^A-Z0-9_-]/g, '')
      .replace(/-+/g, '-')
      .replace(/^[-_]+|[-_]+$/g, '')
      .slice(0, 30);
    return raw || 'BANK';
  };

  const form = useForm<BankFormValues>({
    resolver: zodResolver(bankSchema),
    defaultValues: {
      bankNumber: '',
      bankCode: '',
      fullName: '',
      branch: '',
      iban: '',
      swiftCode: '',
      accountNumber: '',
      contactName: '',
      contactPhone: '',
      notes: '',
      isActive: true,
      accountCode: '',
      currencyCode: currencies[0]?.code || '',
    },
  });

  useEffect(() => {
    setRuntimeCurrencies(currencies || []);
  }, [currencies]);

  const normalize = (value: string) => String(value || '').trim().toLowerCase();
  const isIbanValidFormat = (raw: string) => {
    const iban = String(raw || '').replace(/\s+/g, '');
    if (!iban) return true;
    return /^[A-Za-z]{2}[0-9A-Za-z]{10,32}$/.test(iban);
  };

  const watchedIban = String(form.watch('iban') || '');
  const hasIbanWarning = !isIbanValidFormat(watchedIban);

  const findBestBankAccountCode = (currencyCode: string, bankName: string): string => {
    const list = Array.isArray(accountOptions) ? accountOptions : [];
    if (list.length === 0) return '';

    const bankLike = list.filter((entry) => {
      const label = normalize(entry.label);
      return entry.code.startsWith('1120') || label.includes('بنك') || label.includes('bank');
    });
    const candidates = bankLike.length > 0 ? bankLike : list;

    const normalizedCurrencyCode = normalize(currencyCode);
    const currency = (runtimeCurrencies || []).find((entry) => normalize(entry.code) === normalizedCurrencyCode);
    const currencyTokens = [
      normalizedCurrencyCode,
      normalize(String(currency?.name || '')),
      normalize(String((currency as any)?.nameEn || '')),
      normalize(String(currency?.symbol || '')),
    ].filter(Boolean);

    const nameToken = normalize(bankName);

    const byCurrency = candidates.find((entry) => {
      const label = normalize(entry.label);
      return currencyTokens.some((token) => token && label.includes(token));
    });
    if (byCurrency) return byCurrency.code;

    const byName = candidates.find((entry) => {
      const label = normalize(entry.label);
      return nameToken.length >= 3 && label.includes(nameToken);
    });
    if (byName) return byName.code;

    const exact1120 = candidates.find((entry) => entry.code === '1120');
    if (exact1120) return exact1120.code;

    const startsWith1120 = candidates.find((entry) => entry.code.startsWith('1120'));
    if (startsWith1120) return startsWith1120.code;

    return candidates[0]?.code || '';
  };

  const autoAssignAccountCode = (force = false) => {
    if (!force && accountCodeEditedManually) return;

    const currentAccountCode = String(form.getValues('accountCode') || '').trim();
    if (currentAccountCode && !force) return;

    const nextCode = findBestBankAccountCode(String(form.getValues('currencyCode') || ''), String(form.getValues('fullName') || ''));
    if (!nextCode) return;

    form.setValue('accountCode', nextCode, { shouldDirty: true, shouldValidate: true });
  };

  useEffect(() => {
    if (!open) return;
    autoAssignAccountCode(false);
  }, [open, runtimeCurrencies, accountOptions]);

  const onSubmit = async (values: BankFormValues) => {
    setIsLoading(true);
    try {
      const response = await fetch('/api/banks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...values,
          // API validates legacy fields as required; map full name to them for compatibility.
          name: values.fullName,
          nameEn: values.fullName,
          code: values.bankCode,
          bankCode: values.bankCode,
          accountCode: values.accountCode || undefined,
        }),
      });

      if (!response.ok) {
        const payload = await response.json().catch(() => ({}));
        throw new Error(payload?.error || 'Failed to add bank');
      }

      const newBank = await response.json();
      onBankAdded(newBank);
      toast({
        title: tGlobal?.success,
        description: t?.bankAddedSuccess || 'تم إضافة البنك بنجاح',
      });
      setOpen(false);
      setBankCodeEditedManually(false);
      setAccountCodeEditedManually(false);
      form.reset();
    } catch (error) {
      toast({
        title: tGlobal?.error,
        description:
          (error instanceof Error && error.message) ||
          t?.bankAddedError ||
          'خطأ في إضافة البنك',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      {externalIsOpen === undefined && (
        <DialogTrigger asChild>
          <Button size="sm" variant="outline" className="gap-2">
            <Plus className="h-4 w-4" />
            {t?.addBank || 'إضافة بنك'}
          </Button>
        </DialogTrigger>
      )}
      <DialogContent className="w-[96vw] max-w-3xl max-h-[92vh] overflow-hidden p-0">
        <DialogHeader>
          <div className="px-6 pt-6">
            <DialogTitle>{t?.addNewBank || 'إضافة بنك جديد'}</DialogTitle>
            <DialogDescription>
              {t?.addBankDescription || 'أدخل تفاصيل البنك الجديد'}
            </DialogDescription>
          </div>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="h-full flex flex-col min-h-0">
            <div className="px-6 pb-4 border-b">
              <Tabs defaultValue="bank-data" className="w-full">
                <TabsList className="grid w-full grid-cols-2">
                  <TabsTrigger value="bank-data">{t?.bankDataTab || 'بيانات البنك'}</TabsTrigger>
                  <TabsTrigger value="accounting">{t?.accountingTab || 'المحاسبة'}</TabsTrigger>
                </TabsList>

                <div className="mt-4 max-h-[58vh] overflow-y-auto pe-1">
                  <TabsContent value="bank-data" className="space-y-4 m-0">
                    <div className="rounded-lg border p-4 space-y-4">
                      <p className="text-sm font-medium">{t?.bankCoreInfo || 'البيانات الأساسية'}</p>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <FormField
                          control={form.control}
                          name="bankNumber"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.bankNumber || 'رقم البنك'}</FormLabel>
                              <FormControl>
                                <Input placeholder="سيتم توليده تلقائياً" {...field} value={field.value || ''} readOnly disabled />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={form.control}
                          name="bankCode"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.bankCode || 'رمز البنك'}</FormLabel>
                              <FormControl>
                                <Input
                                  placeholder="ARBK"
                                  {...field}
                                  value={field.value || ''}
                                  onChange={(event) => {
                                    setBankCodeEditedManually(true);
                                    field.onChange(event.target.value);
                                  }}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>

                      <FormField
                        control={form.control}
                        name="fullName"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.bankFullName || 'اسم البنك الكامل'}</FormLabel>
                            <FormControl>
                              <Input
                                placeholder="البنك العربي"
                                {...field}
                                value={field.value || ''}
                                onChange={(event) => {
                                  const nextName = event.target.value;
                                  field.onChange(nextName);
                                  if (!bankCodeEditedManually) {
                                    form.setValue('bankCode', generateBankCode(nextName), { shouldDirty: true, shouldValidate: true });
                                  }
                                  autoAssignAccountCode(false);
                                }}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <FormField
                          control={form.control}
                          name="branch"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.bankBranch || 'فرع البنك'}</FormLabel>
                              <FormControl>
                                <Input placeholder="الفرع الرئيسي" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={form.control}
                          name="currencyCode"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.currency ?? 'العملة'}</FormLabel>
                              <div className="flex items-center gap-2">
                                <div className="flex-1">
                                  <Select
                                    onValueChange={(value) => {
                                      field.onChange(value);
                                      autoAssignAccountCode(false);
                                    }}
                                    value={field.value}
                                  >
                                    <FormControl>
                                      <SelectTrigger>
                                        <SelectValue placeholder={t?.selectCurrency ?? 'اختر العملة'} />
                                      </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                      {runtimeCurrencies.map((currency) => (
                                        <SelectItem key={currency.code} value={currency.code}>
                                          {currency.code} - {currency.name}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                </div>
                                <AddCurrencyDialog
                                  t={t}
                                  tGlobal={tGlobal}
                                  existingCurrencyCodes={runtimeCurrencies.map((currency) => currency.code)}
                                  onCurrencyAdded={(currency) => {
                                    setRuntimeCurrencies((prev) => {
                                      const exists = prev.some((entry) => String(entry.code || '').toUpperCase() === String(currency.code || '').toUpperCase());
                                      if (exists) return prev;
                                      return [...prev, currency];
                                    });
                                    form.setValue('currencyCode', String(currency.code || '').trim(), { shouldDirty: true, shouldValidate: true });
                                    autoAssignAccountCode(true);
                                  }}
                                />
                              </div>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>
                    </div>

                    <div className="rounded-lg border p-4 space-y-4">
                      <p className="text-sm font-medium">{t?.bankAccountInfo || 'بيانات الحساب البنكي'}</p>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <FormField
                          control={form.control}
                          name="iban"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.bankIban || 'رقم حساب البنك IBAN'}</FormLabel>
                              <FormControl>
                                <Input placeholder="JO94CBJO0010000000000131000302" {...field} />
                              </FormControl>
                              {hasIbanWarning && (
                                <p className="text-xs text-amber-600">
                                  {t?.ibanFormatHint || 'تنبيه: صيغة IBAN تبدو غير صحيحة، ويمكنك المتابعة والحفظ.'}
                                </p>
                              )}
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={form.control}
                          name="swiftCode"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.bankSwiftCode || 'رمز SWIFT/BIC'}</FormLabel>
                              <FormControl>
                                <Input placeholder="ARABJOAXXXX" {...field} value={field.value || ''} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>

                      <FormField
                        control={form.control}
                        name="accountNumber"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.bankAccountNumber || 'رقم الحساب البنكي'}</FormLabel>
                            <FormControl>
                              <Input placeholder="001234567890" {...field} value={field.value || ''} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>

                    <div className="rounded-lg border p-4 space-y-4">
                      <p className="text-sm font-medium">{t?.bankContactInfo || 'بيانات التواصل'}</p>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <FormField
                          control={form.control}
                          name="contactName"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.bankContactName || 'اسم جهة الاتصال'}</FormLabel>
                              <FormControl>
                                <Input placeholder="مدير الحساب" {...field} value={field.value || ''} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        <FormField
                          control={form.control}
                          name="contactPhone"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.bankContactPhone || 'هاتف جهة الاتصال'}</FormLabel>
                              <FormControl>
                                <Input placeholder="+9627XXXXXXXX" {...field} value={field.value || ''} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>

                      <FormField
                        control={form.control}
                        name="notes"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.notes || 'ملاحظات'}</FormLabel>
                            <FormControl>
                              <Textarea placeholder={t?.bankNotesPlaceholder || 'أي ملاحظات داخلية عن البنك'} {...field} value={field.value || ''} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                  </TabsContent>

                  <TabsContent value="accounting" className="space-y-4 m-0">
                    <div className="rounded-lg border p-4 space-y-3">
                      <p className="text-sm font-medium">{t?.bankAccountingSection || 'قسم المحاسبة'}</p>
                      <p className="text-xs text-muted-foreground">{t?.bankAccountingSectionHint || 'اربط البنك بحساب شجرة الحسابات ليُستخدم مباشرة في القيود والحركات البنكية.'}</p>
                      <FormField
                        control={form.control}
                        name="accountCode"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.bankAccountLinkLabel || 'الحساب المرتبط في شجرة الحسابات'}</FormLabel>
                            <FormControl>
                              <AccountCodeSelector
                                value={field.value || ''}
                                options={accountOptions}
                                placeholder={t?.bankAccountLinkPlaceholder || 'اختياري - اختر الحساب'}
                                onValueChange={(value) => {
                                  setAccountCodeEditedManually(true);
                                  field.onChange(value);
                                }}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>

                    <div className="rounded-lg border p-4">
                      <FormField
                        control={form.control}
                        name="isActive"
                        render={({ field }) => (
                          <FormItem className="flex items-start gap-3 rounded-md border p-3">
                            <FormControl>
                              <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                            </FormControl>
                            <div className="space-y-1">
                              <FormLabel className="m-0">{t?.bankIsActiveLabel || 'البنك مفعل'}</FormLabel>
                              <p className="text-xs text-muted-foreground">{t?.bankIsActiveHint || 'عند الإيقاف سيبقى البنك محفوظاً لأغراض الأرشفة.'}</p>
                            </div>
                          </FormItem>
                        )}
                      />
                    </div>
                  </TabsContent>
                </div>
              </Tabs>
            </div>

            <div className="px-6 py-4 border-t bg-background/95 backdrop-blur flex gap-2 justify-end">
              <Button
                type="button"
                variant="outline"
                onClick={() => setOpen(false)}
              >
                {tGlobal?.cancel}
              </Button>
              <Button type="submit" disabled={isLoading}>
                {isLoading ? tGlobal?.saving : tGlobal?.save}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
