"use client";

import { useState, useTransition } from "react";
import * as z from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2, Pencil, RefreshCw, Trash2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { AddCurrencyDialog } from "@/components/admin/add-currency-dialog";
import { useDocumentLock } from '@/hooks/use-document-lock';
import { DocumentLockBanner } from '@/components/admin/document-lock-banner';
import { handleRefreshCurrencyRatesNow } from "@/lib/actions";
import type { Currency } from "@/lib/types";

const updateCurrencySchema = z.object({
  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(),
  isDefault: z.boolean().optional(),
});

function EditCurrencyDialog({
  currency,
  t,
  tGlobal,
  sources,
  onSaved,
  onSourceAdded,
}: {
  currency: Currency;
  t: any;
  tGlobal: any;
  sources: string[];
  onSaved: (currency: Currency) => void;
  onSourceAdded?: (src: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const DEFAULT_SOURCE = "https://www.xe.com";
  const CUSTOM_SOURCE = "__custom__";
  const initialSourceInList = currency.source && sources.includes(currency.source) ? currency.source : "";
  const [selectedSource, setSelectedSource] = useState(initialSourceInList || CUSTOM_SOURCE);
  const [customSource, setCustomSource] = useState(
    currency.source && !sources.includes(currency.source || "") ? currency.source || "" : ""
  );
  const { lockStatus } = useDocumentLock('currency', currency.code, { enabled: open });
  const isEditLocked = open && lockStatus.isLocked;

  const form = useForm<z.infer<typeof updateCurrencySchema>>({
    resolver: zodResolver(updateCurrencySchema),
    defaultValues: {
      name: currency.name,
      nameEn: currency.nameEn,
      symbol: currency.symbol,
      exchangeRate: currency.exchangeRate,
      source: currency.source || DEFAULT_SOURCE,
      isDefault: currency.isDefault,
    },
  });

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

    startTransition(async () => {
      try {
        const resolvedSource =
          selectedSource === CUSTOM_SOURCE ? customSource.trim() || DEFAULT_SOURCE : selectedSource || DEFAULT_SOURCE;
        const payload = { ...values, source: resolvedSource };

        const response = await fetch(`/api/currencies/${currency.code}`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        });

        if (!response.ok) {
          throw new Error("Failed to update currency");
        }

        const updated = await response.json();
        onSaved({ ...updated, source: resolvedSource });
        if (onSourceAdded && resolvedSource) onSourceAdded(resolvedSource);
        toast({
          title: tGlobal?.success ?? "Success",
          description: t?.currencyUpdatedSuccess ?? "تم تحديث العملة بنجاح",
        });
        setOpen(false);
      } catch (_error) {
        toast({
          title: tGlobal?.error ?? "Error",
          description: t?.currencyUpdatedError ?? "فشل تحديث العملة",
          variant: "destructive",
        });
      }
    });
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="ghost" size="icon" className="h-8 w-8" title={tGlobal?.edit ?? "تعديل"}>
          <Pencil className="h-4 w-4" />
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t?.editCurrencyTitle ?? "تعديل العملة"}</DialogTitle>
          <DialogDescription>{t?.editCurrencyDescription ?? "تحديث بيانات العملة"}</DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <DocumentLockBanner lockStatus={lockStatus} />
            <FormItem>
              <FormLabel>{t?.currencyCode ?? "رمز العملة"}</FormLabel>
              <FormControl>
                <Input value={currency.code} disabled />
              </FormControl>
            </FormItem>

            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.currencyNameAr ?? "اسم العملة (عربي)"}</FormLabel>
                  <FormControl>
                    <Input {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="nameEn"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.currencyNameEn ?? "اسم العملة (إنجليزي)"}</FormLabel>
                  <FormControl>
                    <Input {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="symbol"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.currencySymbol ?? "الرمز"}</FormLabel>
                  <FormControl>
                    <Input {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="exchangeRate"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t?.exchangeRate ?? "سعر الصرف"}</FormLabel>
                  <FormControl>
                    <Input type="number" step="0.0001" min="0.0001" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormItem>
              <FormLabel>{t?.sourceLabel ?? "المصدر"}</FormLabel>
              <Select value={selectedSource} onValueChange={setSelectedSource}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder={t?.selectSource ?? "اختر المصدر"} />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {sources.map((source) => (
                    <SelectItem key={source} value={source}>
                      {source}
                    </SelectItem>
                  ))}
                  <SelectItem value={CUSTOM_SOURCE}>{t?.customSourceOption ?? "مصدر مخصص"}</SelectItem>
                </SelectContent>
              </Select>
            </FormItem>

            {selectedSource === CUSTOM_SOURCE && (
              <FormItem>
                <FormLabel>{t?.customSourceLabel ?? "المصدر المخصص"}</FormLabel>
                <FormControl>
                  <Input value={customSource} onChange={(event) => setCustomSource(event.target.value)} />
                </FormControl>
              </FormItem>
            )}

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setOpen(false)}>
                {tGlobal?.cancel ?? "إلغاء"}
              </Button>
              <Button type="submit" disabled={isPending || isEditLocked}>
                {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                {tGlobal?.save ?? "حفظ"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}

export default function CurrenciesManagement({
  t,
  tGlobal,
  currencies,
  currentCurrencyCode,
  exchangeRateSources,
}: {
  t: any;
  tGlobal: any;
  currencies: Currency[];
  currentCurrencyCode: string;
  exchangeRateSources?: string[];
}) {
  const { toast } = useToast();
  const [isRatesPending, startRatesTransition] = useTransition();
  const [currencyList, setCurrencyList] = useState<Currency[]>(currencies || []);
  const [pendingCurrencyCode, setPendingCurrencyCode] = useState<string | null>(null);
  const [exchangeSources, setExchangeSources] = useState<string[]>(() => {
    const base = Array.isArray(exchangeRateSources) ? exchangeRateSources : [];
    return Array.from(new Set(["https://www.xe.com", ...base]));
  });

  const upsertSource = (source?: string) => {
    const val = String(source || "").trim();
    if (!val) return;
    setExchangeSources((prev) => (prev.includes(val) ? prev : [...prev, val]));
  };

  const formatCurrencyTimestamp = (value?: string) => {
    if (!value) return "-";
    const dt = new Date(value);
    if (Number.isNaN(dt.getTime())) return "-";
    return dt.toLocaleString("en-US");
  };

  const handleCurrencyAdded = (currency: Currency) => {
    setCurrencyList((prev) => [...prev, currency]);
    upsertSource(currency.source);
  };

  const handleCurrencyUpdated = (currency: Currency) => {
    setCurrencyList((prev) =>
      prev.map((entry) =>
        entry.code === currency.code ? currency : currency.isDefault ? { ...entry, isDefault: false } : entry
      )
    );
    upsertSource(currency.source);
  };

  const handleDeleteCurrency = async (code: string) => {
    setPendingCurrencyCode(code);
    try {
      const response = await fetch(`/api/currencies/${code}`, { method: "DELETE" });
      if (!response.ok) {
        throw new Error("Failed to delete currency");
      }
      setCurrencyList((prev) => prev.filter((entry) => entry.code !== code));
      toast({
        title: tGlobal?.success ?? "Success",
        description: t?.currencyDeletedSuccess ?? "تم حذف العملة بنجاح",
      });
    } catch (_error) {
      toast({
        title: tGlobal?.error ?? "Error",
        description: t?.currencyDeletedError ?? "فشل حذف العملة",
        variant: "destructive",
      });
    } finally {
      setPendingCurrencyCode(null);
    }
  };

  const handleRefreshRates = () => {
    startRatesTransition(async () => {
      const result = await handleRefreshCurrencyRatesNow();
      if (!result?.success) {
        toast({
          title: tGlobal?.error ?? "Error",
          description: t?.currencyRefreshError ?? "فشل تحديث أسعار العملات",
          variant: "destructive",
        });
        return;
      }

      if (Array.isArray(result.currencies)) {
        const refreshedCurrencies = result.currencies as Currency[];
        setCurrencyList(refreshedCurrencies);
        const refreshedSources = refreshedCurrencies
          .map((currency) => String(currency.source || "").trim())
          .filter((source) => source.length > 0);
        setExchangeSources((prev) => Array.from(new Set([...prev, ...refreshedSources])));
      }

      toast({
        title: tGlobal?.success ?? "Success",
        description: (t?.currencyRefreshSuccess ?? "تم تحديث أسعار العملات ({count})").replace(
          "{count}",
          String(result.updatedCount ?? 0)
        ),
      });
    });
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <h3 className="text-lg font-semibold">{t?.currencyManagementTitle ?? "إدارة العملات"}</h3>
          <p className="text-sm text-muted-foreground">{t?.currencyManagementDescription ?? "إضافة وتعديل وحذف العملات"}</p>
        </div>
        <div className="flex items-center gap-2">
          <Button type="button" variant="outline" onClick={handleRefreshRates} disabled={isRatesPending}>
            {isRatesPending ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <RefreshCw className="me-2 h-4 w-4" />}
            {t?.refreshCurrencyRatesButton ?? "تحديث الأسعار"}
          </Button>
          <AddCurrencyDialog
            t={t}
            tGlobal={tGlobal}
            sources={exchangeSources}
            baseCurrencyCode={currentCurrencyCode}
            existingCurrencyCodes={currencyList.map((currency) => currency.code)}
            onCurrencyAdded={handleCurrencyAdded}
            onSourceAdded={upsertSource}
          />
        </div>
      </div>

      <div className="border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t?.currencyReference ?? "الرقم المرجعي"}</TableHead>
              <TableHead>{t?.currencyCode ?? "رمز العملة"}</TableHead>
              <TableHead>{t?.currencyNameAr ?? "اسم العملة (عربي)"}</TableHead>
              <TableHead>{t?.currencySymbol ?? "الرمز"}</TableHead>
              <TableHead>{t?.exchangeRate ?? "سعر الصرف"}</TableHead>
              <TableHead>{t?.lastCurrencyUpdate ?? "آخر تحديث"}</TableHead>
              <TableHead>{t?.defaultCurrencyLabel ?? "العملة الافتراضية"}</TableHead>
              <TableHead className="w-24 text-center">{t?.actions ?? "إجراءات"}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {currencyList.length === 0 && (
              <TableRow>
                <TableCell colSpan={8} className="text-center text-sm text-muted-foreground">
                  {t?.noCurrencies ?? "لا توجد عملات"}
                </TableCell>
              </TableRow>
            )}
            {currencyList.map((currency) => (
              <TableRow key={currency.code}>
                <TableCell>{currency.currencyNumber || "-"}</TableCell>
                <TableCell className="font-medium">{currency.code}</TableCell>
                <TableCell>{currency.name}</TableCell>
                <TableCell>{currency.symbol}</TableCell>
                <TableCell>{currency.exchangeRate}</TableCell>
                <TableCell>{formatCurrencyTimestamp(currency.lastUpdatedAt)}</TableCell>
                <TableCell>{currency.isDefault ? t?.defaultCurrencyLabel ?? "العملة الافتراضية" : "-"}</TableCell>
                <TableCell className="text-center">
                  <div className="flex items-center justify-center gap-1">
                    <EditCurrencyDialog
                      key={currency.code}
                      currency={currency}
                      t={t}
                      tGlobal={tGlobal}
                      sources={exchangeSources}
                      onSourceAdded={upsertSource}
                      onSaved={handleCurrencyUpdated}
                    />
                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8"
                          disabled={currency.isDefault || pendingCurrencyCode === currency.code}
                          title={tGlobal?.delete ?? "حذف"}
                        >
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>{t?.deleteCurrencyTitle ?? "حذف العملة"}</AlertDialogTitle>
                          <AlertDialogDescription>
                            {(t?.deleteCurrencyDescription ?? "هل أنت متأكد من حذف العملة {code}?").replace(
                              "{code}",
                              currency.code
                            )}
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>{tGlobal?.cancel ?? "إلغاء"}</AlertDialogCancel>
                          <AlertDialogAction
                            onClick={() => handleDeleteCurrency(currency.code)}
                            className="bg-destructive hover:bg-destructive/90"
                          >
                            {pendingCurrencyCode === currency.code && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                            {tGlobal?.delete ?? "حذف"}
                          </AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
