"use client";

import { useState, useTransition } from "react";
import { saveSchemaSettings, type SchemaSettings } from "./_actions";

const FIELD_GROUPS: Array<{
  title: string;
  desc: string;
  fields: Array<{
    name: keyof SchemaSettings;
    label: string;
    placeholder?: string;
    type?: "text" | "url" | "email" | "tel" | "date" | "select";
    options?: Array<{ value: string; label: string }>;
    full?: boolean;
  }>;
}> = [
  {
    title: "Tổ chức (Organization)",
    desc: "Thông tin pháp lý hiển thị trong @graph Organization JSON-LD.",
    fields: [
      { name: "organizationName", label: "Tên tổ chức", placeholder: "Finzone Network" },
      {
        name: "organizationLegalName",
        label: "Tên pháp lý",
        placeholder: "Công ty TNHH Finzone Network",
      },
      {
        name: "organizationLogo",
        label: "Logo URL",
        placeholder: "https://...",
        type: "url",
        full: true,
      },
      {
        name: "organizationFoundingDate",
        label: "Ngày thành lập",
        placeholder: "2024-01-15",
        type: "date",
      },
      {
        name: "organizationAddress",
        label: "Địa chỉ",
        placeholder: "Số 1 Đường ABC, Quận 1, TP.HCM",
        full: true,
      },
      {
        name: "organizationPhone",
        label: "Điện thoại",
        placeholder: "+84-...",
        type: "tel",
      },
      {
        name: "organizationEmail",
        label: "Email",
        placeholder: "contact@finzone.io.vn",
        type: "email",
      },
    ],
  },
  {
    title: "Mạng xã hội (sameAs)",
    desc: "Đầy đủ link social → giúp Google liên kết đúng entity.",
    fields: [
      { name: "socialFacebook", label: "Facebook", placeholder: "https://facebook.com/...", type: "url", full: true },
      { name: "socialTwitter", label: "X / Twitter", placeholder: "https://x.com/...", type: "url", full: true },
      { name: "socialYoutube", label: "YouTube", placeholder: "https://youtube.com/...", type: "url", full: true },
      { name: "socialLinkedin", label: "LinkedIn", placeholder: "https://linkedin.com/company/...", type: "url", full: true },
    ],
  },
  {
    title: "Loại Schema",
    desc: "Mặc định cho toàn site.",
    fields: [
      {
        name: "publisherType",
        label: "Publisher type",
        type: "select",
        options: [
          { value: "NewsMediaOrganization", label: "NewsMediaOrganization (báo chí, news site)" },
          { value: "Organization", label: "Organization (tổ chức tổng quát)" },
        ],
      },
      {
        name: "defaultArticleType",
        label: "Loại bài viết mặc định",
        type: "select",
        options: [
          { value: "NewsArticle", label: "NewsArticle (tin tức)" },
          { value: "Article", label: "Article (bài tổng quát)" },
          { value: "BlogPosting", label: "BlogPosting (blog)" },
        ],
      },
    ],
  },
];

export function SchemaForm({ settings }: { settings: SchemaSettings }) {
  const [pending, startTransition] = useTransition();
  const [msg, setMsg] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);

  function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = new FormData(e.currentTarget);
    setMsg(null);
    setErr(null);
    startTransition(async () => {
      const r = await saveSchemaSettings(form);
      if (r.ok) setMsg("Đã lưu cấu hình schema.");
      else setErr(r.error ?? "Lỗi không xác định");
    });
  }

  return (
    <form onSubmit={onSubmit} className="space-y-6">
      {FIELD_GROUPS.map((group) => (
        <section
          key={group.title}
          className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 overflow-hidden"
        >
          <header className="px-4 py-3 border-b border-stroke-subtle bg-bg-elevated/40">
            <h3 className="font-medium">{group.title}</h3>
            <p className="text-xs text-ink-muted mt-0.5">{group.desc}</p>
          </header>
          <div className="p-4 grid grid-cols-1 sm:grid-cols-2 gap-4">
            {group.fields.map((f) => (
              <label
                key={f.name}
                className={`block text-sm ${f.full ? "sm:col-span-2" : ""}`}
              >
                <span className="block text-xs text-ink-muted mb-1">{f.label}</span>
                {f.type === "select" ? (
                  <select
                    name={f.name}
                    defaultValue={settings[f.name] as string}
                    className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm focus:border-accent-primary focus:outline-none"
                  >
                    {f.options?.map((o) => (
                      <option key={o.value} value={o.value}>
                        {o.label}
                      </option>
                    ))}
                  </select>
                ) : (
                  <input
                    type={f.type ?? "text"}
                    name={f.name}
                    defaultValue={settings[f.name] as string}
                    placeholder={f.placeholder}
                    className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm focus:border-accent-primary focus:outline-none"
                  />
                )}
              </label>
            ))}
          </div>
        </section>
      ))}

      <div className="flex items-center gap-3">
        <button
          type="submit"
          disabled={pending}
          className="px-4 py-2 rounded-lg bg-accent-primary text-bg-base text-sm font-medium hover:opacity-90 disabled:opacity-50"
        >
          {pending ? "Đang lưu…" : "Lưu cấu hình"}
        </button>
        {msg && (
          <span className="text-xs text-emerald-300 rounded bg-emerald-500/10 border border-emerald-500/30 px-2 py-1.5">
            ✓ {msg}
          </span>
        )}
        {err && (
          <span className="text-xs text-rose-300 rounded bg-rose-500/10 border border-rose-500/30 px-2 py-1.5">
            ❌ {err}
          </span>
        )}
      </div>
    </form>
  );
}
