"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { updateSettingsAction } from "./_actions";
import { SECRET_PLACEHOLDER } from "./_constants";

export type SettingItem = {
  key: string;
  value: string;
  isSecret: boolean;
};

export type SettingsGroup = {
  category: string;
  title: string;
  description: string;
  items: SettingItem[];
};

function labelFor(key: string): string {
  // ai.openai_api_key → "openai api key"
  const parts = key.split(".");
  const last = parts[parts.length - 1] ?? key;
  return last.replace(/_/g, " ");
}

function placeholderFor(key: string): string {
  switch (key) {
    case "site.title":
      return "Finzone v2";
    case "site.url":
      return "https://v2.finzone.io.vn";
    case "site.locale":
      return "vi-VN";
    case "ai.openai_base_url":
      return "https://api.openai.com/v1";
    case "ai.openai_model":
      return "gpt-4o-mini";
    case "seo.default_focus_min_score":
      return "70";
    default:
      return "";
  }
}

function isLongText(key: string): boolean {
  return key.endsWith(".description") || key.endsWith(".note");
}

export function SettingsForm({ group }: { group: SettingsGroup }) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [msg, setMsg] = useState<string | null>(null);

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setMsg(null);
    const fd = new FormData(e.currentTarget);
    startTransition(async () => {
      const res = await updateSettingsAction(group.category, fd);
      if (res.ok) {
        setMsg(
          res.updated === 0
            ? "Không có gì thay đổi."
            : `Đã cập nhật ${res.updated} mục.`,
        );
        router.refresh();
      }
    });
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-5 mb-6"
    >
      <h2 className="font-display font-semibold text-lg mb-1">{group.title}</h2>
      <p className="text-sm text-ink-muted mb-4">{group.description}</p>

      <div className="space-y-3">
        {group.items.map((item) => (
          <div key={item.key}>
            <label className="text-xs font-medium text-ink-muted block mb-1">
              <span className="capitalize">{labelFor(item.key)}</span>
              {item.isSecret && (
                <span className="ml-2 text-[10px] uppercase tracking-wider text-amber-300">
                  secret
                </span>
              )}
              <span className="ml-2 font-mono text-[10px] text-ink-muted/60">{item.key}</span>
            </label>
            {isLongText(item.key) ? (
              <textarea
                name={item.key}
                rows={2}
                defaultValue={item.value}
                placeholder={placeholderFor(item.key)}
                className="w-full px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
              />
            ) : (
              <input
                name={item.key}
                type={item.isSecret ? "password" : "text"}
                defaultValue={
                  item.isSecret && item.value
                    ? ""
                    : item.value
                }
                placeholder={
                  item.isSecret && item.value
                    ? SECRET_PLACEHOLDER
                    : placeholderFor(item.key)
                }
                className="w-full px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary font-mono"
              />
            )}
          </div>
        ))}
      </div>

      <div className="flex items-center justify-between mt-5 pt-4 border-t border-stroke-subtle">
        {msg ? (
          <span className="text-sm text-emerald-300">{msg}</span>
        ) : (
          <span className="text-xs text-ink-muted">
            Để trống ô secret nếu không muốn đổi.
          </span>
        )}
        <button
          type="submit"
          disabled={pending}
          className="px-4 py-2 rounded-lg bg-accent-primary text-white text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition"
        >
          {pending ? "Đang lưu…" : "Lưu thay đổi"}
        </button>
      </div>
    </form>
  );
}
