"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { Loader2, Settings2 } from "lucide-react";
import SearchableSelect from "@/components/ui/SearchableSelect";
import { useApiFetch } from "@/hooks/useApiFetch";
import { AlertMessage } from "@/components/ui/AlertMessage";
import { ModalShell } from "@/components/ui/ModalShell";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";

export interface OffsetSettings {
  id: string;
  offset1: string;
  user_id: string;
  default_currency: string;
  currency_total: string;
}

export interface CommonSettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function CommonSettingsModal({
  isOpen,
  onClose,
}: CommonSettingsModalProps) {
  const [settings, setSettings] = useState<OffsetSettings | null>(null);
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState<string | null>(null);
  const [selectedCurrency, setSelectedCurrency] = useState<{
    label: string;
    value: string | number;
  } | null>(null);
  const [offset1, setOffset1] = useState<string>("");

  const { data: fetchData, loading, error, fetchData: fetchApiData, reset } = useApiFetch<
    | { success: boolean; data?: OffsetSettings }
    | OffsetSettings
  >({
    onSuccess: async (json) => {
      const data =
        json && typeof json === "object" && "data" in json && json.data
          ? json.data
          : (json as OffsetSettings);
      if (data && typeof data === "object" && "id" in data) {
        setSettings(data);
        if (data.offset1 !== undefined) {
          setOffset1(String(data.offset1));
        }
        if (data.default_currency) {
          const idOrCode = data.default_currency;
          setSelectedCurrency({ label: idOrCode, value: idOrCode });
          try {
            const res = await fetch("/api/searchabledropdown/currencylist", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: "{}",
              credentials: "include",
            });
            const listData = await res.json();
            const rawOptions = Array.isArray(listData) ? listData : listData?.data;
            const options = Array.isArray(rawOptions) ? rawOptions : [];
            const match = options.find(
              (o: { value?: string; label?: string }) =>
                String(o?.value ?? "") === String(idOrCode) ||
                String(o?.label ?? "") === String(idOrCode)
            );
            if (match) {
              setSelectedCurrency({
                label: String(match.label ?? match.value ?? idOrCode),
                value: String(match.value ?? match.label ?? idOrCode),
              });
            }
          } catch {
            setSelectedCurrency({ label: idOrCode, value: idOrCode });
          }
        }
      }
    },
  });

  const loadSettings = useCallback(async () => {
    await fetchApiData("/api/offset-settings");
  }, [fetchApiData]);

  const hasLoadedForOpenRef = useRef(false);

  useEffect(() => {
    if (isOpen) {
      if (!hasLoadedForOpenRef.current) {
        hasLoadedForOpenRef.current = true;
        loadSettings();
      }
    } else {
      hasLoadedForOpenRef.current = false;
      setSettings(null);
      setSelectedCurrency(null);
      setOffset1("");
      setSuccess(null);
      reset();
    }
  }, [isOpen, loadSettings, reset]);

  const handleSave = async () => {
    if (!selectedCurrency || !settings) {
      return;
    }

    const selectedCurrencyId = String(selectedCurrency.value);

    setSaving(true);
    setSuccess(null);
    reset();

    try {
      const result = await fetchApiData("/api/offset-settings", {
        id: settings.id,
        currency_id: selectedCurrencyId,
        default_currency: selectedCurrencyId,
        offset1: offset1,
        user_id: settings.user_id,
      });

      if (result && (result as any).success) {
        setSuccess("Settings updated successfully");
        await loadSettings();
        setTimeout(() => {
          onClose();
        }, 1500);
      }
    } catch (err) {
      // Error is handled by useApiFetch
    } finally {
      setSaving(false);
    }
  };

  return (
    /**
     * Rebuilt on `ModalShell`: the dialog now has a focus trap, Escape
     * handling, scroll lock and `aria-modal`, none of which the previous bare
     * fixed div provided. Two blurred blobs and the gradient header wash are
     * gone, and the offset input no longer drives its focus ring from four
     * inline React handlers — it is the shadcn `Input`.
     */
    <ModalShell
      isOpen={isOpen}
      onClose={onClose}
      size="lg"
      icon={<Settings2 />}
      eyebrow="Settings"
      title="Common settings"
      description="Configure the default currency and system offsets."
      footer={
        !loading && !(error && !settings) ? (
          <>
            <Button variant="outline" onClick={onClose} disabled={saving}>
              Cancel
            </Button>
            <Button onClick={handleSave} disabled={saving || !selectedCurrency}>
              {saving && <Loader2 className="size-4 animate-spin" aria-hidden />}
              {saving ? "Saving…" : "Save changes"}
            </Button>
          </>
        ) : undefined
      }
    >
      {loading ? (
        <div className="space-y-6" role="status" aria-live="polite">
          <div className="space-y-2">
            <Skeleton className="h-3.5 w-32" />
            <Skeleton className="h-9 w-full" />
          </div>
          <div className="space-y-2">
            <Skeleton className="h-3.5 w-24" />
            <Skeleton className="h-9 w-full" />
          </div>
          <span className="sr-only">Loading settings…</span>
        </div>
      ) : error && !settings ? (
        <div className="space-y-3">
          <AlertMessage type="error" message={error} onDismiss={() => reset()} />
          <Button variant="outline" onClick={loadSettings}>
            Try again
          </Button>
        </div>
      ) : (
        <div className="space-y-6">
          <div className="space-y-2">
            <Label htmlFor="default-currency">Default currency</Label>
            <SearchableSelect
              label=""
              apiUrl="/api/searchabledropdown/currencylist"
              value={selectedCurrency}
              onChange={setSelectedCurrency}
              placeholder="Select default currency…"
            />
            <p className="text-xs text-muted-foreground">
              Used wherever a report does not specify its own currency.
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="offset1">Offset 1</Label>
            <Input
              id="offset1"
              type="text"
              value={offset1}
              onChange={(e) => setOffset1(e.target.value)}
              placeholder="Enter offset value"
            />
            <p className="text-xs text-muted-foreground">
              The offset applied to system-wide calculations.
            </p>
          </div>

          {error && <AlertMessage type="error" message={error} onDismiss={() => reset()} />}
          {success && <AlertMessage type="success" message={success} />}
        </div>
      )}
    </ModalShell>
  );
}
