'use client';

import { useEffect, useMemo, 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 { Currency } from '@/lib/types';
import { BUILTIN_CURRENCY_CATALOG } from '@/lib/currency-catalog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

const currencySchema = z.object({
  code: z.string().min(1, 'Currency code is required').max(5),
  name: z.string().min(1, 'Arabic name is required'),
  nameEn: z.string().min(1, 'English name is required'),
  symbol: z.string().min(1, 'Symbol is required').max(3),
  exchangeRate: z.coerce.number().min(0.0001, 'Exchange rate must be positive'),
  source: z.string().optional(),
});

type CurrencyFormValues = z.infer<typeof currencySchema>;

interface AddCurrencyDialogProps {
  onCurrencyAdded: (currency: Currency) => void;
  onSourceAdded?: (source: string) => void;
  t: any;
  tGlobal: any;
  baseCurrencyCode?: string;
  sources?: string[];
  existingCurrencyCodes?: string[];
}

const CUSTOM_CURRENCY_OPTION = '__custom_currency__';

export function AddCurrencyDialog({
  onCurrencyAdded,
  onSourceAdded,
  t,
  tGlobal,
  baseCurrencyCode = 'JOD',
  sources = ['https://www.xe.com'],
  existingCurrencyCodes = [],
}: AddCurrencyDialogProps) {
  const [open, setOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isFetchingRate, setIsFetchingRate] = useState(false);
  const DEFAULT_SOURCE = sources[0] || 'https://www.xe.com';
  const CUSTOM_SOURCE = '__custom__';
  const [sourceOptions, setSourceOptions] = useState<string[]>(() => Array.from(new Set([DEFAULT_SOURCE, ...sources])));
  const [selectedSource, setSelectedSource] = useState<string>(DEFAULT_SOURCE);
  const [customSource, setCustomSource] = useState('');
  const [selectedCatalogCode, setSelectedCatalogCode] = useState<string>(() => {
    const existingCodes = new Set(existingCurrencyCodes.map((code) => String(code || '').trim().toUpperCase()).filter(Boolean));
    const firstAvailable = BUILTIN_CURRENCY_CATALOG.find((currency) => !existingCodes.has(currency.code));
    return firstAvailable?.code || CUSTOM_CURRENCY_OPTION;
  });
  const { toast } = useToast();

  const existingCurrencyCodeSet = useMemo(
    () => new Set(existingCurrencyCodes.map((code) => String(code || '').trim().toUpperCase()).filter(Boolean)),
    [existingCurrencyCodes]
  );

  const availableCatalog = useMemo(
    () => BUILTIN_CURRENCY_CATALOG.filter((currency) => !existingCurrencyCodeSet.has(currency.code)),
    [existingCurrencyCodeSet]
  );

  const selectedCatalogCurrency =
    selectedCatalogCode === CUSTOM_CURRENCY_OPTION
      ? null
      : BUILTIN_CURRENCY_CATALOG.find((currency) => currency.code === selectedCatalogCode) || null;
  const isCustomCurrency = selectedCatalogCode === CUSTOM_CURRENCY_OPTION;

  const form = useForm<CurrencyFormValues>({
    resolver: zodResolver(currencySchema),
    defaultValues: {
      code: '',
      name: '',
      nameEn: '',
      symbol: '',
      exchangeRate: 1,
      source: DEFAULT_SOURCE,
    },
  });

  useEffect(() => {
    if (!open || !selectedCatalogCurrency) return;
    form.setValue('code', selectedCatalogCurrency.code);
    form.setValue('name', selectedCatalogCurrency.name);
    form.setValue('nameEn', selectedCatalogCurrency.nameEn);
    form.setValue('symbol', selectedCatalogCurrency.symbol);

    const baseCode = String(baseCurrencyCode || '').trim().toUpperCase() || 'JOD';
    if (selectedCatalogCurrency.code === baseCode) {
      form.setValue('exchangeRate', 1);
    }
  }, [open, selectedCatalogCurrency, baseCurrencyCode, form]);

  const fetchExchangeRate = async () => {
    const targetCode = form.getValues('code').trim().toUpperCase();
    const base = (baseCurrencyCode || '').trim().toUpperCase() || 'JOD';
    if (!targetCode) {
      toast({ title: tGlobal?.error, description: t?.currencyCodeRequired || 'أدخل رمز العملة أولاً.', variant: 'destructive' });
      return;
    }
    if (targetCode === base) {
      form.setValue('code', targetCode);
      form.setValue('exchangeRate', 1);
      form.setValue('source', DEFAULT_SOURCE);
      setSelectedSource(DEFAULT_SOURCE);
      toast({ title: tGlobal?.success, description: t?.exchangeRateBaseSame || 'هذه هي العملة الأساسية، تم تعيين 1.0000.' });
      return;
    }

    setIsFetchingRate(true);
    try {
      const res = await fetch(`https://api.exchangerate.host/latest?base=${base}&symbols=${targetCode}`);
      const data = await res.json();
      const rate = data?.rates?.[targetCode];
      if (!rate || Number(rate) <= 0) {
        throw new Error('Rate not found');
      }
      form.setValue('code', targetCode);
      form.setValue('exchangeRate', Number(rate));
      form.setValue('source', 'exchangerate.host');
      setSelectedSource('exchangerate.host');
      setSourceOptions((prev) => (prev.includes('exchangerate.host') ? prev : [...prev, 'exchangerate.host']));
      toast({ title: tGlobal?.success, description: t?.exchangeRateFetched || 'تم جلب سعر الصرف تلقائياً.' });
    } catch (error) {
      toast({ title: tGlobal?.error, description: t?.exchangeRateFetchError || 'تعذر جلب سعر الصرف، أدخل القيمة يدوياً.', variant: 'destructive' });
    } finally {
      setIsFetchingRate(false);
    }
  };

  const onSubmit = async (values: CurrencyFormValues) => {
    setIsLoading(true);
    try {
      const payload = selectedCatalogCurrency
        ? {
            ...values,
            code: selectedCatalogCurrency.code,
            name: selectedCatalogCurrency.name,
            nameEn: selectedCatalogCurrency.nameEn,
            symbol: selectedCatalogCurrency.symbol,
          }
        : values;
      const normalizedCode = String(payload.code || '').trim().toUpperCase();
      if (existingCurrencyCodeSet.has(normalizedCode)) {
        toast({
          title: tGlobal?.error,
          description: t?.currencyCodeDuplicate || 'رمز العملة موجود مسبقاً.',
          variant: 'destructive',
        });
        return;
      }

      const resolvedSource = selectedSource === CUSTOM_SOURCE ? (customSource.trim() || DEFAULT_SOURCE) : (selectedSource || DEFAULT_SOURCE);
      const response = await fetch('/api/currencies', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...payload,
          code: normalizedCode,
          source: resolvedSource,
          isDefault: false,
        }),
      });

      if (!response.ok) {
        const errorPayload = await response.json().catch(() => ({}));
        const errorMessage = String(errorPayload?.error || 'Failed to add currency');
        throw new Error(errorMessage);
      }

      const newCurrency = await response.json();
      const finalCurrency = { ...newCurrency, source: resolvedSource };
      onCurrencyAdded(finalCurrency as Currency);
      if (resolvedSource && onSourceAdded) onSourceAdded(resolvedSource);
      if (resolvedSource && !sourceOptions.includes(resolvedSource)) {
        setSourceOptions((prev) => [...prev, resolvedSource]);
      }
      toast({
        title: tGlobal?.success,
        description: t?.currencyAddedSuccess || 'تم إضافة العملة بنجاح',
      });
      setOpen(false);
      setSelectedSource(DEFAULT_SOURCE);
      setCustomSource('');
      const firstAvailable = BUILTIN_CURRENCY_CATALOG.find((currency) => !existingCurrencyCodeSet.has(currency.code));
      setSelectedCatalogCode(firstAvailable?.code || CUSTOM_CURRENCY_OPTION);
      form.reset({ code: '', name: '', nameEn: '', symbol: '', exchangeRate: 1, source: DEFAULT_SOURCE });
    } catch (error) {
      const errorMessage = String((error as Error)?.message || '');
      toast({
        title: tGlobal?.error,
        description: errorMessage.includes('already exists')
          ? (t?.currencyCodeDuplicate || 'رمز العملة موجود مسبقاً.')
          : (t?.currencyAddedError || 'خطأ في إضافة العملة'),
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleCatalogChange = (value: string) => {
    setSelectedCatalogCode(value);
    if (value === CUSTOM_CURRENCY_OPTION) {
      form.setValue('code', '');
      form.setValue('name', '');
      form.setValue('nameEn', '');
      form.setValue('symbol', '');
      return;
    }

    const selected = BUILTIN_CURRENCY_CATALOG.find((entry) => entry.code === value);
    if (!selected) return;

    form.setValue('code', selected.code);
    form.setValue('name', selected.name);
    form.setValue('nameEn', selected.nameEn);
    form.setValue('symbol', selected.symbol);

    const baseCode = String(baseCurrencyCode || '').trim().toUpperCase() || 'JOD';
    if (selected.code === baseCode) {
      form.setValue('exchangeRate', 1);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button size="sm" variant="outline" className="gap-2">
          <Plus className="h-4 w-4" />
          {t?.addCurrency || 'إضافة عملة'}
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t?.addNewCurrency || 'إضافة عملة جديدة'}</DialogTitle>
          <DialogDescription>
            {t?.addCurrencyDescription || 'أدخل سعر الصرف بالنسبة للعملة الأساسية (دينار أردني)'}
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormItem>
              <FormLabel>{t?.currencyCatalogLabel || 'اختيار من قائمة العملات'}</FormLabel>
              <Select value={selectedCatalogCode} onValueChange={handleCatalogChange}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder={t?.currencyCatalogPlaceholder || 'اختر عملة جاهزة'} />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {availableCatalog.map((currency) => (
                    <SelectItem key={currency.code} value={currency.code}>
                      {currency.code} - {currency.name}
                    </SelectItem>
                  ))}
                  <SelectItem value={CUSTOM_CURRENCY_OPTION}>
                    {t?.customCurrencyOption || 'عملة غير موجودة في القائمة'}
                  </SelectItem>
                </SelectContent>
              </Select>
            </FormItem>

            <FormField
              control={form.control}
              name="code"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.currencyCode || 'رمز العملة'}</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="USD, EUR, GBP"
                      {...field}
                      disabled={!isCustomCurrency}
                      onChange={(event) => field.onChange(event.target.value.toUpperCase())}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.currencyNameAr || 'اسم العملة (عربي)'}</FormLabel>
                  <FormControl>
                    <Input placeholder="دولار أمريكي" {...field} disabled={!isCustomCurrency} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="nameEn"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.currencyNameEn || 'Currency Name (English)'}</FormLabel>
                  <FormControl>
                    <Input placeholder="US Dollar" {...field} disabled={!isCustomCurrency} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="symbol"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.currencySymbol || 'الرمز'}</FormLabel>
                  <FormControl>
                    <Input placeholder="$, €, £" maxLength={5} {...field} disabled={!isCustomCurrency} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="exchangeRate"
              render={({ field }) => (
                <FormItem>
                  <div className="flex items-center justify-between gap-3">
                    <FormLabel>{t?.exchangeRate || 'سعر الصرف (مقابل الدينار)'}</FormLabel>
                    <Button type="button" size="sm" variant="outline" onClick={fetchExchangeRate} disabled={isFetchingRate || isLoading}>
                      {isFetchingRate ? (tGlobal?.loading || '...') : (t?.fetchRate || 'جلب تلقائي')}
                    </Button>
                  </div>
                  <FormControl>
                    <Input
                      type="number"
                      step="0.0001"
                      placeholder="0.71"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="source"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.exchangeRateSource || 'مصدر سعر الصرف'}</FormLabel>
                  <Select
                    value={selectedSource}
                    onValueChange={(val) => {
                      setSelectedSource(val);
                      if (val !== CUSTOM_SOURCE) {
                        form.setValue('source', val);
                        if (!sourceOptions.includes(val)) setSourceOptions((prev) => [...prev, val]);
                      }
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={t?.exchangeRateSource || 'مصدر سعر الصرف'} />
                    </SelectTrigger>
                    <SelectContent>
                      {sourceOptions.map((src) => (
                        <SelectItem key={src} value={src}>{src}</SelectItem>
                      ))}
                      <SelectItem value={CUSTOM_SOURCE}>{t?.customSourceLabel || 'إدخال مصدر جديد'}</SelectItem>
                    </SelectContent>
                  </Select>
                  {selectedSource === CUSTOM_SOURCE && (
                    <div className="mt-2">
                      <Input
                        placeholder="https://www.xe.com"
                        value={customSource}
                        onChange={(e) => {
                          setCustomSource(e.target.value);
                          form.setValue('source', e.target.value);
                        }}
                      />
                    </div>
                  )}
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="flex gap-2 justify-end pt-4">
              <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>
  );
}
