"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { X } from "lucide-react";
import SearchableSelect from "@/components/ui/SearchableSelect";
import { useApiFetch } from "@/hooks/useApiFetch";
import { AlertMessage } from "@/components/ui/AlertMessage";
import { PRIMARY_COLOR, PRIMARY_COLOR_HOVER, type CSSPropertiesWithVars } from "@/lib/common";

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;
  } | 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;
    }

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

    try {
      const result = await fetchApiData("/api/offset-settings", {
        id: settings.id,
        default_currency: selectedCurrency.value,
        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);
    }
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 px-4 py-6 backdrop-blur-sm"
      onClick={onClose}
    >
      <div
        className="relative w-full max-w-2xl overflow-hidden rounded-lg border border-white/30 bg-white/95 shadow-2xl ring-1 ring-black/10"
        onClick={(event) => event.stopPropagation()}
      >
        <div
          className="absolute -right-20 -top-24 h-48 w-48 rounded-lg blur-3xl"
          style={{ backgroundColor: `${PRIMARY_COLOR}1A` }}
        />
        <div
          className="absolute -bottom-24 -left-16 h-48 w-48 rounded-lg blur-3xl"
          style={{ backgroundColor: `${PRIMARY_COLOR}26` }}
        />

        <div
          className="relative flex items-start justify-between border-b border-slate-100 bg-gradient-to-r via-white to-white px-6 py-5"
          style={{
            background: `linear-gradient(to right, ${PRIMARY_COLOR}0D, white, white)`,
          }}
        >
          <div>
            <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
              Settings
            </p>
            <h2 className="mt-1 text-2xl font-semibold text-slate-800">
              Common Settings
            </h2>
            <p className="mt-1 text-xs font-medium text-slate-500">
              Configure default currency and system settings
            </p>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="rounded-lg border border-slate-200 bg-white/70 p-2 text-slate-400 shadow-sm transition hover:-translate-y-0.5 hover:border-red-300 hover:bg-red-50 hover:text-red-500"
            aria-label="Close modal"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        <div className="relative px-6 pb-6 pt-5">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <div className="text-sm text-slate-500">Loading settings...</div>
            </div>
          ) : error && !settings ? (
            <div className="py-12">
              <AlertMessage
                type="error"
                message={error}
                onDismiss={() => reset()}
              />
              <button
                onClick={loadSettings}
                className="mt-3 rounded-lg border border-red-300 bg-white px-4 py-2 text-sm font-medium text-red-700 transition hover:bg-red-100"
              >
                Retry
              </button>
            </div>
          ) : (
            <div className="space-y-6">
              {/* Default Currency Selection */}
              <div className="space-y-2">
                <label className="block text-sm font-semibold text-slate-700">
                  Default Currency
                </label>
                <SearchableSelect
                  label=""
                  apiUrl="/api/searchabledropdown/currencylist"
                  value={selectedCurrency}
                  onChange={setSelectedCurrency}
                  placeholder="Select default currency..."
                />
                <p className="text-xs text-slate-500">
                  Select the default currency for your system
                </p>
              </div>

              {/* Offset1 Input */}
              <div className="space-y-2">
                <label className="block text-sm font-semibold text-slate-700">
                  Offset 1
                </label>
                <input
                  type="text"
                  value={offset1}
                  onChange={(e) => setOffset1(e.target.value)}
                  className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700 shadow-sm transition focus:outline-none focus:ring-2"
                  style={{
                    "--focus-border": PRIMARY_COLOR,
                    "--focus-ring": `${PRIMARY_COLOR}4D`,
                  } as CSSPropertiesWithVars}
                  onFocus={(e) => {
                    e.currentTarget.style.borderColor = PRIMARY_COLOR;
                    e.currentTarget.style.boxShadow = `0 0 0 2px ${PRIMARY_COLOR}4D`;
                  }}
                  onBlur={(e) => {
                    e.currentTarget.style.borderColor = "";
                    e.currentTarget.style.boxShadow = "";
                  }}
                  placeholder="Enter offset value"
                />
                <p className="text-xs text-slate-500">
                  Enter the offset value for your system
                </p>
              </div>

              {/* Error Message */}
              {error && (
                <AlertMessage
                  type="error"
                  message={error}
                  onDismiss={() => reset()}
                />
              )}

              {/* Success Message */}
              {success && (
                <AlertMessage type="success" message={success} />
              )}

              {/* Action Buttons */}
              <div className="flex items-center justify-end gap-3 border-t border-slate-100 pt-4">
                <button
                  type="button"
                  onClick={onClose}
                  className="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-600 shadow-sm transition hover:bg-slate-50"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={handleSave}
                  disabled={saving || !selectedCurrency}
                  className="rounded-lg border px-4 py-2 text-sm font-semibold text-white shadow-sm transition disabled:cursor-not-allowed disabled:opacity-50"
                  style={{
                    borderColor: PRIMARY_COLOR,
                    backgroundColor: PRIMARY_COLOR,
                  }}
                  onMouseEnter={(e) => {
                    if (!saving && selectedCurrency) e.currentTarget.style.backgroundColor = PRIMARY_COLOR_HOVER;
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = PRIMARY_COLOR;
                  }}
                >
                  {saving ? "Saving..." : "Save Changes"}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

