"use client";

import { useState, useTransition } from "react";
import { Save, Eye, EyeOff, Check, RotateCcw } from "lucide-react";

type SettingRow = {
  key: string;
  category: string;
  description: string | null;
  envFallback: string | null;
  default: string;
  secret: boolean;
  value: string;
  isSet: boolean;
};

type Props = {
  category: "ai" | "site" | "seo";
  title: string;
  hint: string;
  settings: SettingRow[];
  action: (category: string, formData: FormData) => Promise<{ ok: boolean; changedCount: number }>;
};

/**
 * Generic settings form. Renders one input per setting.
 * Secret fields show "•••• kept" until the user types — that sentinel
 * tells the server action "leave value alone" so we don't accidentally
 * blank an API key by submitting the form without changes.
 */
export function SettingsForm({ category, title, hint, settings, action }: Props) {
  const [pending, startTransition] = useTransition();
  const [savedAt, setSavedAt] = useState<number | null>(null);
  const [revealed, setRevealed] = useState<Record<string, boolean>>({});

  return (
    <form
      action={(fd) => {
        startTransition(async () => {
          await action(category, fd);
          setSavedAt(Date.now());
        });
      }}
      className="space-y-5"
    >
      <div>
        <h1 className="font-display text-ink-primary text-2xl font-semibold lg:text-3xl">
          {title}
        </h1>
        <p className="text-ink-secondary mt-1 text-sm">{hint}</p>
      </div>

      <div className="border-stroke-subtle bg-bg-elevated/40 divide-stroke-subtle/50 divide-y rounded-xl border">
        {settings.map((s) => {
          const isSecret = s.secret;
          const showRaw = !!revealed[s.key];
          const placeholder = isSecret
            ? s.value || "(chưa thiết lập — đang dùng env hoặc mặc định)"
            : s.default;

          return (
            <div key={s.key} className="grid gap-2 p-4 lg:grid-cols-3 lg:gap-6 lg:p-5">
              <div className="lg:col-span-1">
                <label className="text-ink-primary block text-sm font-medium">
                  {labelOf(s.key)}
                </label>
                <code className="text-ink-muted mt-0.5 block text-[11px]">{s.key}</code>
                {s.description ? (
                  <p className="text-ink-secondary mt-1 text-xs leading-relaxed">{s.description}</p>
                ) : null}
                {s.envFallback ? (
                  <p className="text-ink-muted mt-1 text-[11px]">
                    env fallback: <code>{s.envFallback}</code>
                  </p>
                ) : null}
              </div>

              <div className="lg:col-span-2">
                {isLongField(s.key) ? (
                  <textarea
                    name={s.key}
                    rows={3}
                    defaultValue={s.value}
                    placeholder={placeholder}
                    className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold w-full resize-y rounded-md border px-3 py-2 font-mono text-sm focus:outline-none"
                  />
                ) : (
                  <div className="flex items-center gap-2">
                    <input
                      name={s.key}
                      type={isSecret && !showRaw ? "password" : "text"}
                      defaultValue={s.value}
                      placeholder={placeholder}
                      autoComplete="off"
                      className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold w-full rounded-md border px-3 py-2 font-mono text-sm focus:outline-none"
                    />
                    {isSecret ? (
                      <button
                        type="button"
                        onClick={() => setRevealed((r) => ({ ...r, [s.key]: !r[s.key] }))}
                        className="text-ink-muted hover:text-brand-gold border-stroke-default rounded-md border p-2"
                        title={showRaw ? "Ẩn" : "Hiện"}
                      >
                        {showRaw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </button>
                    ) : null}
                  </div>
                )}
                <div className="mt-1.5 flex items-center justify-between text-[11px]">
                  <span className={s.isSet ? "text-emerald-400" : "text-ink-muted"}>
                    {s.isSet ? "✓ Đã thiết lập (override)" : "○ Đang dùng env / default"}
                  </span>
                  {s.isSet ? (
                    <button
                      type="button"
                      onClick={(e) => {
                        const form = e.currentTarget.closest("form");
                        if (!form) return;
                        const input = form.elements.namedItem(s.key) as HTMLInputElement | null;
                        if (input) input.value = "";
                      }}
                      className="text-ink-muted hover:text-brand-red flex items-center gap-1"
                      title="Để trống → quay về env/default"
                    >
                      <RotateCcw className="h-3 w-3" />
                      Reset
                    </button>
                  ) : null}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="flex items-center gap-3">
        <button
          type="submit"
          disabled={pending}
          className="bg-brand-gold text-bg-base inline-flex items-center gap-2 rounded-md px-5 py-2.5 text-sm font-semibold hover:brightness-105 active:translate-y-px disabled:opacity-60"
        >
          <Save className="h-4 w-4" />
          {pending ? "Đang lưu..." : "Lưu thay đổi"}
        </button>
        {savedAt ? (
          <span className="inline-flex items-center gap-1 text-xs text-emerald-400">
            <Check className="h-3.5 w-3.5" />
            Đã lưu lúc {new Date(savedAt).toLocaleTimeString("vi-VN")}
          </span>
        ) : null}
      </div>
    </form>
  );
}

function isLongField(key: string): boolean {
  return key === "site.disclaimer";
}

function labelOf(key: string): string {
  const map: Record<string, string> = {
    "ai.provider": "Provider",
    "ai.openai_api_key": "OpenAI API Key",
    "ai.openai_base_url": "OpenAI Base URL (endpoint)",
    "ai.openai_model": "OpenAI Model",
    "ai.anthropic_api_key": "Anthropic API Key",
    "ai.anthropic_model": "Anthropic Model",
    "ai.daily_limit_free": "Free tier daily limit",
    "site.name": "Tên site",
    "site.url": "URL công khai (canonical domain)",
    "site.tagline": "Tagline",
    "site.contact_email": "Email liên hệ",
    "site.disclaimer": "Disclaimer (footer)",
    "seo.ga_id": "Google Analytics ID",
    "seo.gtm_id": "Google Tag Manager ID",
  };
  return map[key] ?? key;
}
