"use client";

import { useCallback, useEffect, useState } from "react";
import { useTranslations } from "next-intl";

interface AiSettings {
  provider: string;
  base_url: string;
  model: string;
  enabled: boolean;
  has_api_key: boolean;
  api_key_masked: string | null;
}

interface SeoPost {
  title: string;
  slug: string;
  meta_title: string;
  meta_description: string;
  keywords: string[];
  short_description: string;
  content_html: string;
}

const card = "rounded-xl border border-[#1e2235] bg-[#0f1120] p-5";
const label = "block text-xs font-medium text-gray-400 mb-1";
const input =
  "w-full rounded-lg border border-[#262b40] bg-[#0c0e1a] px-3 py-2 text-sm text-gray-100 outline-none focus:border-indigo-500";
const btn =
  "rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500 disabled:opacity-50";
const btnGhost =
  "rounded-lg border border-[#262b40] px-4 py-2 text-sm text-gray-300 hover:bg-[#161a2e] disabled:opacity-50";

export function AiContentStudio() {
  const t = useTranslations("auto.adminAi");

  const [settings, setSettings] = useState<AiSettings | null>(null);
  const [apiKey, setApiKey] = useState("");
  const [savingSettings, setSavingSettings] = useState(false);
  const [settingsMsg, setSettingsMsg] = useState<string | null>(null);

  // Generation form
  const [description, setDescription] = useState("");
  const [title, setTitle] = useState("");
  const [type, setType] = useState("");
  const [tags, setTags] = useState("");
  const [keyword, setKeyword] = useState("");
  const [audience, setAudience] = useState("");
  const [locale, setLocale] = useState("fa");

  const [generating, setGenerating] = useState(false);
  const [genError, setGenError] = useState<string | null>(null);
  const [post, setPost] = useState<SeoPost | null>(null);
  const [publishNow, setPublishNow] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saveMsg, setSaveMsg] = useState<string | null>(null);

  const loadSettings = useCallback(async () => {
    const res = await fetch("/api/admin/ai/settings", { cache: "no-store" });
    if (res.ok) setSettings(await res.json());
  }, []);

  useEffect(() => {
    loadSettings();
  }, [loadSettings]);

  const saveSettings = async () => {
    if (!settings) return;
    setSavingSettings(true);
    setSettingsMsg(null);
    const res = await fetch("/api/admin/ai/settings", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        provider: settings.provider,
        base_url: settings.base_url,
        model: settings.model,
        enabled: settings.enabled,
        api_key: apiKey.trim() === "" ? null : apiKey.trim(),
      }),
    });
    if (res.ok) {
      setSettings(await res.json());
      setApiKey("");
      setSettingsMsg(t("settingsSaved"));
    } else {
      setSettingsMsg(t("settingsError"));
    }
    setSavingSettings(false);
  };

  const generate = async () => {
    setGenerating(true);
    setGenError(null);
    setSaveMsg(null);
    const res = await fetch("/api/admin/ai/generate", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        description,
        title: title || null,
        type: type || null,
        tags: tags ? tags.split(",").map((s) => s.trim()).filter(Boolean) : null,
        keyword: keyword || null,
        audience: audience || null,
        locale,
      }),
    });
    const data = await res.json().catch(() => null);
    if (res.ok) setPost(data);
    else setGenError(data?.error ?? t("generateError"));
    setGenerating(false);
  };

  const saveAsBlog = async () => {
    if (!post) return;
    setSaving(true);
    setSaveMsg(null);
    const res = await fetch("/api/admin/ai/save", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        slug: post.slug,
        title: post.title,
        short_description: post.short_description,
        content: post.content_html,
        meta_title: post.meta_title,
        meta_description: post.meta_description,
        meta_keywords: post.keywords.join(", "),
        include_in_site_map: true,
        is_published: publishNow,
      }),
    });
    setSaveMsg(res.ok ? t("savedAsBlog") : t("saveError"));
    setSaving(false);
  };

  const setPostField = (k: keyof SeoPost, v: string) =>
    setPost((p) => (p ? { ...p, [k]: v } : p));

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-xl font-semibold text-white">{t("pageTitle")}</h1>
        <p className="mt-1 text-sm text-gray-400">{t("pageDesc")}</p>
      </div>

      {/* ── Settings ─────────────────────────────────────────── */}
      <section className={card}>
        <h2 className="text-sm font-semibold text-white">{t("settingsTitle")}</h2>
        <p className="mt-1 text-xs text-gray-500">{t("settingsDesc")}</p>
        {settings && (
          <div className="mt-4 grid gap-4 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <label className={label}>{t("apiKeyLabel")}</label>
              <input
                className={input}
                type="password"
                placeholder={settings.api_key_masked ?? t("apiKeyPlaceholder")}
                value={apiKey}
                onChange={(e) => setApiKey(e.target.value)}
              />
              <p className="mt-1 text-[11px] text-gray-500">
                {settings.has_api_key ? `✓ ${t("keyConfigured")}` : t("noKey")}
              </p>
            </div>
            <div>
              <label className={label}>{t("baseUrlLabel")}</label>
              <input
                className={input}
                value={settings.base_url}
                onChange={(e) => setSettings({ ...settings, base_url: e.target.value })}
              />
            </div>
            <div>
              <label className={label}>{t("modelLabel")}</label>
              <input
                className={input}
                value={settings.model}
                onChange={(e) => setSettings({ ...settings, model: e.target.value })}
              />
            </div>
            <label className="flex items-center gap-2 text-sm text-gray-300">
              <input
                type="checkbox"
                checked={settings.enabled}
                onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })}
              />
              {t("enabledLabel")}
            </label>
            <div className="flex items-center gap-3 sm:col-span-2">
              <button className={btn} onClick={saveSettings} disabled={savingSettings}>
                {savingSettings ? t("saving") : t("saveSettings")}
              </button>
              {settingsMsg && <span className="text-xs text-gray-400">{settingsMsg}</span>}
            </div>
          </div>
        )}
      </section>

      {/* ── Generator ────────────────────────────────────────── */}
      <section className={card}>
        <h2 className="text-sm font-semibold text-white">{t("generateTitle")}</h2>
        <p className="mt-1 text-xs text-gray-500">{t("generateDesc")}</p>
        {settings && !settings.enabled && (
          <p className="mt-3 rounded-lg bg-amber-500/10 px-3 py-2 text-xs text-amber-300">
            {t("mustConfigure")}
          </p>
        )}
        <div className="mt-4 grid gap-4">
          <div>
            <label className={label}>{t("descriptionLabel")}</label>
            <textarea
              className={`${input} min-h-[100px]`}
              placeholder={t("descriptionPlaceholder")}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className={label}>{t("titleLabel")}</label>
              <input className={input} value={title} onChange={(e) => setTitle(e.target.value)} />
            </div>
            <div>
              <label className={label}>{t("typeLabel")}</label>
              <input className={input} placeholder={t("typePlaceholder")} value={type} onChange={(e) => setType(e.target.value)} />
            </div>
            <div>
              <label className={label}>{t("keywordLabel")}</label>
              <input className={input} value={keyword} onChange={(e) => setKeyword(e.target.value)} />
            </div>
            <div>
              <label className={label}>{t("audienceLabel")}</label>
              <input className={input} value={audience} onChange={(e) => setAudience(e.target.value)} />
            </div>
            <div>
              <label className={label}>{t("tagsLabel")}</label>
              <input className={input} value={tags} onChange={(e) => setTags(e.target.value)} />
            </div>
            <div>
              <label className={label}>{t("localeLabel")}</label>
              <select className={input} value={locale} onChange={(e) => setLocale(e.target.value)}>
                <option value="fa">{t("localeFa")}</option>
                <option value="en">{t("localeEn")}</option>
              </select>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <button className={btn} onClick={generate} disabled={generating || !description.trim()}>
              {generating ? t("generating") : t("generate")}
            </button>
            {genError && <span className="text-xs text-red-400">{genError}</span>}
          </div>
        </div>
      </section>

      {/* ── Result ───────────────────────────────────────────── */}
      {post && (
        <section className={card}>
          <h2 className="text-sm font-semibold text-white">{t("resultTitle")}</h2>
          <div className="mt-4 grid gap-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <div>
                <label className={label}>{t("fTitle")}</label>
                <input className={input} value={post.title} onChange={(e) => setPostField("title", e.target.value)} />
              </div>
              <div>
                <label className={label}>{t("fSlug")}</label>
                <input className={input} value={post.slug} onChange={(e) => setPostField("slug", e.target.value)} />
              </div>
              <div>
                <label className={label}>{t("fMetaTitle")}</label>
                <input className={input} value={post.meta_title} onChange={(e) => setPostField("meta_title", e.target.value)} />
              </div>
              <div>
                <label className={label}>{t("fKeywords")}</label>
                <input className={input} value={post.keywords.join(", ")} onChange={(e) => setPost({ ...post, keywords: e.target.value.split(",").map((s) => s.trim()).filter(Boolean) })} />
              </div>
            </div>
            <div>
              <label className={label}>{t("fMetaDesc")}</label>
              <textarea className={`${input} min-h-[60px]`} value={post.meta_description} onChange={(e) => setPostField("meta_description", e.target.value)} />
            </div>
            <div>
              <label className={label}>{t("fShortDesc")}</label>
              <textarea className={`${input} min-h-[60px]`} value={post.short_description} onChange={(e) => setPostField("short_description", e.target.value)} />
            </div>
            <div>
              <label className={label}>{t("fContent")}</label>
              <textarea className={`${input} min-h-[200px] font-mono text-xs`} value={post.content_html} onChange={(e) => setPostField("content_html", e.target.value)} />
            </div>
            <div>
              <label className={label}>{t("preview")}</label>
              <div
                className="prose prose-invert max-w-none rounded-lg border border-[#262b40] bg-white p-4 text-black"
                dangerouslySetInnerHTML={{ __html: post.content_html }}
              />
            </div>
            <div className="flex flex-wrap items-center gap-3">
              <label className="flex items-center gap-2 text-sm text-gray-300">
                <input type="checkbox" checked={publishNow} onChange={(e) => setPublishNow(e.target.checked)} />
                {t("publishNow")}
              </label>
              <button className={btnGhost} onClick={saveAsBlog} disabled={saving}>
                {saving ? t("saving") : t("saveAsBlog")}
              </button>
              {saveMsg && <span className="text-xs text-gray-400">{saveMsg}</span>}
            </div>
          </div>
        </section>
      )}
    </div>
  );
}
