'use client';

import { useMemo, useState } from 'react';
import * as z from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/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 { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import { useDocumentLock } from '@/hooks/use-document-lock';
import { AddBankDialog } from './add-bank-dialog';
import { DocumentLockBanner } from './document-lock-banner';
import type { Bank, Currency, ChartOfAccount } from '@/lib/types';
import { Pencil, Trash2 } from 'lucide-react';
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().optional(),
  bankCode: z.string().trim().min(2).max(30).regex(/^[A-Za-z0-9_-]+$/),
  fullName: z.string().min(1),
  branch: z.string().optional(),
  iban: z.string().trim().max(34).optional().or(z.literal('')),
  swiftCode: z.string().optional(),
  accountNumber: z.string().optional(),
  contactName: z.string().optional(),
  contactPhone: z.string().optional(),
  notes: z.string().optional(),
  isActive: z.coerce.boolean().optional().default(true),
  accountCode: z.string().optional(),
  currencyCode: z.string().min(1),
});

type BankValues = z.infer<typeof bankSchema>;

export function BanksManager({
  initialBanks,
  currencies,
  chartOfAccounts,
  t,
  tGlobal,
}: {
  initialBanks: Bank[];
  currencies: Currency[];
  chartOfAccounts: ChartOfAccount[];
  t: any;
  tGlobal: any;
}) {
  const { toast } = useToast();
  const [banks, setBanks] = useState<Bank[]>(initialBanks);
  const [editing, setEditing] = useState<Bank | null>(null);
  const [search, setSearch] = useState('');
  const [runtimeCurrencies, setRuntimeCurrencies] = useState<Currency[]>(currencies);
  const accountOptions: AccountCodeOption[] = useMemo(
    () => (chartOfAccounts || [])
      .filter((acc) => acc.type === 'account')
      .map((acc) => ({ code: acc.code, label: `${acc.code} - ${acc.nameAr}` })),
    [chartOfAccounts],
  );

  const form = useForm<BankValues>({
    resolver: zodResolver(bankSchema),
    defaultValues: {
      bankNumber: '',
      bankCode: '',
      fullName: '',
      branch: '',
      iban: '',
      swiftCode: '',
      accountNumber: '',
      contactName: '',
      contactPhone: '',
      notes: '',
      isActive: true,
      accountCode: '',
      currencyCode: currencies[0]?.code || '',
    },
  });

  const filteredBanks = useMemo(() => {
    const q = search.toLowerCase().trim();
    if (!q) return banks;
    return banks.filter((b) =>
      [b.fullName, b.name, b.bankNumber, b.code, b.branch, b.iban, b.currencyCode]
        .filter(Boolean)
        .some((v) => String(v).toLowerCase().includes(q))
    );
  }, [banks, search]);

  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 watchedEditIban = String(form.watch('iban') || '');
  const hasIbanWarning = !isIbanValidFormat(watchedEditIban);
  const { lockStatus } = useDocumentLock('bank', editing?.id || '', { enabled: !!editing?.id });
  const isEditLocked = !!editing && lockStatus.isLocked;

  const startEdit = (bank: Bank) => {
    setEditing(bank);
    form.reset({
      bankNumber: String(bank.bankNumber || bank.code || ''),
      bankCode: String(bank.code || ''),
      fullName: String(bank.fullName || bank.name || ''),
      branch: String(bank.branch || ''),
      iban: String(bank.iban || ''),
      swiftCode: String(bank.swiftCode || ''),
      accountNumber: String(bank.accountNumber || ''),
      contactName: String(bank.contactName || ''),
      contactPhone: String(bank.contactPhone || ''),
      notes: String(bank.notes || ''),
      isActive: bank.isActive !== false,
      accountCode: String(bank.accountCode || ''),
      currencyCode: String(bank.currencyCode || currencies[0]?.code || ''),
    });
  };

  const onUpdate = async (values: BankValues) => {
    if (!editing) return;
    if (isEditLocked) return;

    const response = await fetch('/api/banks', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: editing.id, ...values, name: values.fullName, nameEn: values.fullName, code: values.bankCode, bankCode: values.bankCode, accountCode: values.accountCode || undefined }),
    });

    if (!response.ok) {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.bankUpdateError ?? 'تعذر تحديث البنك', variant: 'destructive' });
      return;
    }

    const updated = await response.json();
    setBanks((prev) => prev.map((b) => (b.id === updated.id ? updated : b)));
    setEditing(null);
    toast({ title: tGlobal?.success ?? 'نجاح', description: t?.bankUpdatedSuccess ?? 'تم تحديث البنك بنجاح' });
  };

  const onDelete = async (id: string) => {
    const confirmed = typeof window !== 'undefined' ? window.confirm(t?.confirmDeleteBank ?? 'هل تريد حذف البنك؟') : true;
    if (!confirmed) return;

    const response = await fetch(`/api/banks?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
    if (!response.ok) {
      toast({ title: tGlobal?.error ?? 'خطأ', description: t?.bankDeleteError ?? 'تعذر حذف البنك', variant: 'destructive' });
      return;
    }

    setBanks((prev) => prev.filter((b) => b.id !== id));
    toast({ title: tGlobal?.success ?? 'نجاح', description: t?.bankDeletedSuccess ?? 'تم حذف البنك' });
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t?.manageBanks ?? 'إدارة البنوك'}</CardTitle>
        <CardDescription>{t?.manageBanksDescription ?? 'إضافة وتعديل وحذف البنوك المستخدمة في النظام.'}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
          <Input
            placeholder={t?.searchBanks ?? 'بحث عن بنك...'}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="md:max-w-sm"
          />
          <AddBankDialog
            currencies={currencies}
            accountOptions={accountOptions}
            t={t}
            tGlobal={tGlobal}
            onBankAdded={(bank) => setBanks((prev) => [bank, ...prev])}
          />
        </div>

        <div className="rounded-md border overflow-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t?.bankNumber ?? 'رقم البنك'}</TableHead>
                <TableHead>{t?.bankCode ?? 'رمز البنك'}</TableHead>
                <TableHead>{t?.bankFullName ?? 'اسم البنك الكامل'}</TableHead>
                <TableHead>{t?.bankBranch ?? 'فرع البنك'}</TableHead>
                <TableHead>{t?.bankIban ?? 'IBAN'}</TableHead>
                <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                <TableHead>{t?.bankAccountLinkLabel ?? 'الحساب المحاسبي'}</TableHead>
                <TableHead className="text-right">{t?.actions ?? 'إجراءات'}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredBanks.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                    {t?.noBanks ?? 'لا توجد بنوك'}
                  </TableCell>
                </TableRow>
              ) : (
                filteredBanks.map((bank) => (
                  <TableRow key={bank.id}>
                    <TableCell>{bank.bankNumber || bank.code || '-'}</TableCell>
                    <TableCell>{bank.code || '-'}</TableCell>
                    <TableCell className="font-medium">{bank.fullName || bank.name || '-'}</TableCell>
                    <TableCell>{bank.branch || '-'}</TableCell>
                    <TableCell>{bank.iban || '-'}</TableCell>
                    <TableCell>{bank.currencyCode || '-'}</TableCell>
                    <TableCell>{bank.accountCode || '-'}</TableCell>
                    <TableCell className="text-right">
                      <div className="inline-flex items-center gap-1">
                        <Button type="button" size="icon" variant="outline" onClick={() => startEdit(bank)}>
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button type="button" size="icon" variant="destructive" onClick={() => onDelete(bank.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>

      <Dialog open={!!editing} onOpenChange={(open) => { if (!open) setEditing(null); }}>
        <DialogContent className="w-[96vw] max-w-3xl max-h-[92vh] overflow-hidden p-0">
          <DialogHeader>
            <div className="px-6 pt-6">
              <DialogTitle>{t?.editBank ?? 'تعديل البنك'}</DialogTitle>
              <DialogDescription className="sr-only">{t?.editBankDescription ?? 'قم بتعديل بيانات البنك ثم احفظ التغييرات.'}</DialogDescription>
            </div>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onUpdate)} className="h-full flex flex-col min-h-0">
              <div className="px-6 pt-2">
                <DocumentLockBanner lockStatus={lockStatus} />
              </div>
              <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 {...field} value={field.value || ''} readOnly disabled /></FormControl>
                              <FormMessage />
                            </FormItem>
                          )} />
                          <FormField control={form.control} name="bankCode" render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.bankCode ?? 'رمز البنك'}</FormLabel>
                              <FormControl><Input {...field} /></FormControl>
                              <FormMessage />
                            </FormItem>
                          )} />
                        </div>

                        <FormField control={form.control} name="fullName" render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.bankFullName ?? 'اسم البنك الكامل'}</FormLabel>
                            <FormControl><Input {...field} /></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 {...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={field.onChange} value={field.value}>
                                    <FormControl>
                                      <SelectTrigger>
                                        <SelectValue />
                                      </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 });
                                  }}
                                />
                              </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 {...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 {...field} value={field.value || ''} /></FormControl>
                              <FormMessage />
                            </FormItem>
                          )} />
                        </div>
                        <FormField control={form.control} name="accountNumber" render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.bankAccountNumber || 'رقم الحساب البنكي'}</FormLabel>
                            <FormControl><Input {...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 {...field} value={field.value || ''} /></FormControl>
                              <FormMessage />
                            </FormItem>
                          )} />
                          <FormField control={form.control} name="contactPhone" render={({ field }) => (
                            <FormItem>
                              <FormLabel>{t?.bankContactPhone || 'هاتف جهة الاتصال'}</FormLabel>
                              <FormControl><Input {...field} value={field.value || ''} /></FormControl>
                              <FormMessage />
                            </FormItem>
                          )} />
                        </div>
                        <FormField control={form.control} name="notes" render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.notes || 'ملاحظات'}</FormLabel>
                            <FormControl><Textarea {...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>
                        <FormField control={form.control} name="accountCode" render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.bankAccountLinkLabel || 'الحساب المرتبط في شجرة الحسابات'}</FormLabel>
                            <FormControl>
                              <AccountCodeSelector
                                value={field.value || ''}
                                options={accountOptions}
                                placeholder={t?.bankAccountLinkPlaceholder || 'اختياري - اختر الحساب'}
                                onValueChange={field.onChange}
                              />
                            </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={() => setEditing(null)}>
                  {tGlobal?.cancel ?? 'إلغاء'}
                </Button>
                <Button type="submit" disabled={isEditLocked}>{tGlobal?.save ?? 'حفظ'}</Button>
              </div>
            </form>
          </Form>
        </DialogContent>
      </Dialog>
    </Card>
  );
}
