"use client";

/**
 * ویرایشگر مقاله مجله: متن با نوار ابزار (تیتر، لینک، عکس، کارت محصول، دکمه CTA)،
 * پرسش‌های متداول، محصولات مرتبط، و پنل زنده سئو/GEO با بهینه‌سازی خودکار و پیشنهاد هوش مصنوعی.
 */
import { useRouter } from "next/navigation";
import { useMemo, useRef, useState, useTransition, type ReactNode } from "react";
import { Icon } from "@/components/ui/Icon";
import { faNumber } from "@/lib/format";
import { slugifyFa } from "@/lib/persian";
import { autoOptimizeArticle, checkArticle, SEO_DESC_RANGE, SEO_TITLE_RANGE } from "@/lib/seo-check";
import { saveArticleAction, type ArticleInput } from "@/server/admin/magazine";
import { suggestArticleSeoAction } from "@/server/admin/ai";
import { uploadMediaAction } from "@/server/admin/images";
import { ImageField } from "./ImageField";

export interface ArticleFormValue {
  title: string;
  slug: string;
  excerpt: string;
  body: string;
  coverUrl: string;
  coverAlt: string;
  seoTitle: string;
  seoDescription: string;
  focusKeyword: string;
  faq: { q: string; a: string }[];
  ctaLabel: string;
  ctaHref: string;
  productIds: number[];
  authorName: string;
}

interface Props {
  id: string | null;
  initial: ArticleFormValue;
  published: boolean;
  products: { id: number; name: string; brand: string }[];
  aiEnabled: boolean;
  siteUrl: string;
}

const STATUS_STYLE = { good: "bg-ink", warn: "bg-muted", bad: "bg-paper ring-1 ring-ink" } as const;

function Field({ label, error, hint, children }: { label: string; error?: string; hint?: ReactNode; children: ReactNode }) {
  return (
    <label className="block">
      <span className="label flex items-center justify-between gap-2">
        {label}
        {hint && <span className="text-[11px] font-normal text-muted">{hint}</span>}
      </span>
      {children}
      {error && <span className="mt-1 block text-xs font-medium">⚠ {error}</span>}
    </label>
  );
}

export function ArticleForm({ id, initial, published, products, aiEnabled, siteUrl }: Props) {
  const router = useRouter();
  const [f, setF] = useState(initial);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [notice, setNotice] = useState("");
  const [pending, start] = useTransition();
  const [aiBusy, setAiBusy] = useState(false);
  const [imgBusy, setImgBusy] = useState(false);
  const bodyRef = useRef<HTMLTextAreaElement>(null);
  const imgInput = useRef<HTMLInputElement>(null);
  const [productPick, setProductPick] = useState("");

  const set = <K extends keyof ArticleFormValue>(k: K, v: ArticleFormValue[K]) => setF((p) => ({ ...p, [k]: v }));
  const seo = useMemo(() => checkArticle(f), [f]);
  const productName = (pid: number) => products.find((p) => p.id === pid)?.name ?? `محصول ${pid}`;

  /** درج متن در محل نشانگر متن مقاله */
  function insert(before: string, after = "", placeholder = "") {
    const el = bodyRef.current;
    if (!el) return;
    const { selectionStart: s, selectionEnd: e, value } = el;
    const selected = value.slice(s, e) || placeholder;
    const next = value.slice(0, s) + before + selected + after + value.slice(e);
    set("body", next);
    requestAnimationFrame(() => {
      el.focus();
      el.setSelectionRange(s + before.length, s + before.length + selected.length);
    });
  }
  const insertBlock = (block: string) => insert(`\n\n${block}\n\n`);

  async function uploadInline(file: File) {
    setImgBusy(true);
    const fd = new FormData();
    fd.set("file", file);
    const res = await uploadMediaAction("articles", fd).catch(() => ({ ok: false as const, error: "ارتباط با سرور قطع شد" }));
    setImgBusy(false);
    if (imgInput.current) imgInput.current.value = "";
    if (!res.ok) return setNotice(`⚠ ${res.error}`);
    insertBlock(`![${f.title}](${res.url})`);
  }

  function autoOptimize() {
    setF((p) => autoOptimizeArticle(p));
    setNotice("فیلدهای خالی سئو پر شدند و طول‌ها اصلاح شد. قبل از ذخیره بررسی کنید.");
  }

  async function aiSuggest() {
    setAiBusy(true);
    setNotice("");
    const res = await suggestArticleSeoAction({ title: f.title, body: f.body, focusKeyword: f.focusKeyword }).catch(() => ({ ok: false as const, error: "ارتباط با سرور قطع شد" }));
    setAiBusy(false);
    if (!res.ok) return setNotice(`⚠ ${res.error}`);
    setF((p) => ({
      ...p,
      seoTitle: res.seoTitle || p.seoTitle,
      seoDescription: res.seoDescription || p.seoDescription,
      focusKeyword: p.focusKeyword || res.focusKeyword || "",
      excerpt: p.excerpt.trim().length >= 20 ? p.excerpt : res.excerpt || p.excerpt,
      faq: p.faq.length ? p.faq : res.faq,
    }));
    setNotice("پیشنهادهای هوش مصنوعی اعمال شد (فقط فیلدهای سئو، پرسش‌های متداول خالی و خلاصه خالی). قبل از انتشار بخوانید.");
  }

  function save(publish: boolean) {
    setNotice("");
    start(async () => {
      const input: ArticleInput = { ...f, publish, slug: f.slug || undefined, coverAlt: f.coverAlt || undefined };
      const res = await saveArticleAction(id, input);
      if (!res.ok) {
        setErrors(res.errors);
        setNotice("⚠ لطفاً خطاهای مشخص‌شده را اصلاح کنید");
        return;
      }
      setErrors({});
      router.push(`/admin/magazine/${res.id}?saved=${publish ? "published" : "draft"}`);
      router.refresh();
    });
  }

  const fullTitle = `${f.seoTitle || f.title || "عنوان مقاله"} | زهورا`;
  const metaDesc = f.seoDescription || f.excerpt || "توضیحات متا…";
  const slug = f.slug || slugifyFa(f.title);

  return (
    <div className="grid gap-4 lg:grid-cols-[1fr_340px]">
      <div className="min-w-0 space-y-4">
        {notice && <p role="status" className="rounded-xl bg-paper px-4 py-3 text-sm ring-1 ring-line">{notice}</p>}

        <section className="space-y-4 rounded-2xl bg-paper p-5">
          <Field label="عنوان مقاله" error={errors.title}>
            <input className="field" maxLength={120} value={f.title} onChange={(e) => set("title", e.target.value)} />
          </Field>
          <Field label="آدرس (URL) سفارشی" error={errors.slug} hint={<bdi dir="ltr">/mag/{slug || "…"}</bdi>}>
            <input className="field" maxLength={90} placeholder="خالی = از روی عنوان" value={f.slug} onChange={(e) => set("slug", e.target.value)} />
          </Field>
          <Field label="خلاصه (نمایش در فهرست مجله)" error={errors.excerpt} hint={`${faNumber(f.excerpt.length)}/۳۰۰`}>
            <textarea className="field h-20 py-3" maxLength={300} value={f.excerpt} onChange={(e) => set("excerpt", e.target.value)} />
          </Field>

          <div>
            <span className="label">متن مقاله</span>
            <div className="flex flex-wrap gap-1 rounded-t-xl border border-b-0 border-line bg-mist p-1.5 text-xs">
              <button type="button" className="chip h-8" onClick={() => insert("\n\n## ", "\n\n", "تیتر بخش")}>تیتر</button>
              <button type="button" className="chip h-8" onClick={() => insert("\n\n### ", "\n\n", "تیتر فرعی")}>تیتر فرعی</button>
              <button type="button" className="chip h-8 font-bold" onClick={() => insert("**", "**", "متن پررنگ")}>پررنگ</button>
              <button type="button" className="chip h-8" onClick={() => insert("\n- ", "", "مورد فهرست")}>فهرست</button>
              <button type="button" className="chip h-8" onClick={() => insert("\n> ", "\n", "نقل‌قول")}>نقل‌قول</button>
              <button type="button" className="chip h-8" onClick={() => insert("[", "](/c/مراقبت-پوست)", "متن لینک")}>لینک</button>
              <button type="button" className="chip h-8" disabled={imgBusy} onClick={() => imgInput.current?.click()}>{imgBusy ? "تبدیل به WebP…" : "عکس"}</button>
              <select
                className="chip h-8 max-w-44"
                value=""
                aria-label="درج کارت محصول"
                onChange={(e) => e.target.value && insertBlock(`[[product:${e.target.value}]]`)}
              >
                <option value="">+ کارت محصول</option>
                {products.map((p) => <option key={p.id} value={p.id}>{p.brand} · {p.name}</option>)}
              </select>
              <button type="button" className="chip h-8" onClick={() => insertBlock("[[cta:مشاهده محصولات|/c/مراقبت-پوست]]")}>دکمه CTA</button>
              <input ref={imgInput} type="file" accept="image/*,.heic,.heif" className="sr-only" tabIndex={-1} onChange={(e) => e.target.files?.[0] && void uploadInline(e.target.files[0])} />
            </div>
            <textarea
              ref={bodyRef}
              className="field min-h-[420px] rounded-t-none py-3 font-mono text-[13px] leading-7"
              value={f.body}
              onChange={(e) => set("body", e.target.value)}
              aria-label="متن مقاله"
            />
            {errors.body && <span className="mt-1 block text-xs font-medium">⚠ {errors.body}</span>}
            <p className="mt-2 text-[11px] leading-5 text-muted">
              ## تیتر · **پررنگ** · [متن](/آدرس) · ![توضیح عکس](آدرس) · <bdi dir="ltr">[[product:13]]</bdi> کارت محصول · <bdi dir="ltr">[[cta:متن دکمه|/آدرس]]</bdi> دکمه
            </p>
          </div>
        </section>

        <section className="space-y-3 rounded-2xl bg-paper p-5">
          <div className="flex items-center justify-between">
            <h2 className="text-sm font-bold">پرسش‌های متداول (FAQ)</h2>
            <button type="button" className="chip h-8 text-xs" disabled={f.faq.length >= 10} onClick={() => set("faq", [...f.faq, { q: "", a: "" }])}>
              <Icon name="plus" size={14} /> پرسش
            </button>
          </div>
          <p className="text-[11px] leading-5 text-muted">پاسخ‌های کوتاه و دقیق در گوگل به‌صورت «پرسش و پاسخ» و در پاسخ موتورهای هوش مصنوعی (GEO) نقل می‌شوند.</p>
          {f.faq.map((item, i) => (
            <div key={i} className="space-y-2 rounded-xl border border-line p-3">
              <input className="field h-10" placeholder="پرسش" value={item.q} onChange={(e) => set("faq", f.faq.map((x, j) => (j === i ? { ...x, q: e.target.value } : x)))} />
              <textarea className="field h-20 py-2" placeholder="پاسخ کوتاه و دقیق" value={item.a} onChange={(e) => set("faq", f.faq.map((x, j) => (j === i ? { ...x, a: e.target.value } : x)))} />
              {(errors[`faq.${i}.q`] || errors[`faq.${i}.a`]) && <span className="block text-xs">⚠ {errors[`faq.${i}.q`] ?? errors[`faq.${i}.a`]}</span>}
              <button type="button" className="text-xs text-muted underline" onClick={() => set("faq", f.faq.filter((_, j) => j !== i))}>حذف</button>
            </div>
          ))}
        </section>

        <section className="space-y-4 rounded-2xl bg-paper p-5">
          <h2 className="text-sm font-bold">هدایت خواننده (CTA و محصولات)</h2>
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="متن دکمه پایان مقاله" error={errors.ctaLabel}>
              <input className="field h-10" maxLength={40} placeholder="مثلاً: خرید ضدآفتاب‌ها" value={f.ctaLabel} onChange={(e) => set("ctaLabel", e.target.value)} />
            </Field>
            <Field label="لینک دکمه" error={errors.ctaHref}>
              <input className="field h-10" dir="ltr" maxLength={200} placeholder="/ یا /p/13 یا /c/..." value={f.ctaHref} onChange={(e) => set("ctaHref", e.target.value)} />
            </Field>
          </div>
          <div className="flex flex-wrap gap-2 text-xs">
            <button type="button" className="chip h-8" onClick={() => setF((p) => ({ ...p, ctaHref: "/", ctaLabel: p.ctaLabel || "رفتن به فروشگاه" }))}>صفحه اصلی</button>
            {f.productIds[0] && (
              <button type="button" className="chip h-8" onClick={() => setF((p) => ({ ...p, ctaHref: `/p/${p.productIds[0]}`, ctaLabel: p.ctaLabel || "خرید همین محصول" }))}>
                اولین محصول مرتبط
              </button>
            )}
          </div>
          <div>
            <span className="label">محصولات مرتبط (پایان مقاله)</span>
            <div className="flex gap-2">
              <select className="field h-10" value={productPick} onChange={(e) => setProductPick(e.target.value)} aria-label="انتخاب محصول مرتبط">
                <option value="">انتخاب محصول…</option>
                {products.filter((p) => !f.productIds.includes(p.id)).map((p) => <option key={p.id} value={p.id}>{p.brand} · {p.name}</option>)}
              </select>
              <button
                type="button"
                className="btn-outline h-10 shrink-0 px-4"
                disabled={!productPick || f.productIds.length >= 8}
                onClick={() => {
                  set("productIds", [...f.productIds, Number(productPick)]);
                  setProductPick("");
                }}
              >
                افزودن
              </button>
            </div>
            <div className="mt-2 flex flex-wrap gap-2">
              {f.productIds.map((pid) => (
                <span key={pid} className="chip h-8 text-xs">
                  {productName(pid)}
                  <button type="button" aria-label="حذف" onClick={() => set("productIds", f.productIds.filter((x) => x !== pid))}><Icon name="close" size={12} /></button>
                </span>
              ))}
            </div>
          </div>
        </section>
      </div>

      <aside className="space-y-4">
        <section className="space-y-3 rounded-2xl bg-paper p-5">
          <p className="text-sm">وضعیت: <strong>{published ? "منتشرشده" : "پیش‌نویس"}</strong></p>
          <button type="button" className="btn-primary w-full" disabled={pending} onClick={() => save(true)}>{pending ? "در حال ذخیره…" : published ? "ذخیره و به‌روزرسانی" : "انتشار"}</button>
          <button type="button" className="btn-outline w-full" disabled={pending} onClick={() => save(false)}>{published ? "برگرداندن به پیش‌نویس" : "ذخیره پیش‌نویس"}</button>
          {id && <a href={`/mag/${encodeURIComponent(slug)}?preview=1`} target="_blank" className="block text-center text-xs underline">پیش‌نمایش در سایت</a>}
          <Field label="نویسنده (اختیاری)">
            <input className="field h-10" maxLength={60} value={f.authorName} onChange={(e) => set("authorName", e.target.value)} />
          </Field>
        </section>

        <section className="space-y-3 rounded-2xl bg-paper p-5">
          <ImageField name="coverUrl" target="articles" initialUrl={f.coverUrl} label="عکس کاور" onChange={(u) => set("coverUrl", u)} />
          <Field label="متن جایگزین کاور (Alt)" error={errors.coverAlt}>
            <input className="field h-10" maxLength={140} value={f.coverAlt} onChange={(e) => set("coverAlt", e.target.value)} />
          </Field>
        </section>

        <section className="space-y-3 rounded-2xl bg-paper p-5">
          <div className="flex items-center justify-between">
            <h2 className="text-sm font-bold">سئو و GEO</h2>
            <span className="rounded-full bg-mist px-3 py-1 text-xs font-bold">امتیاز {faNumber(seo.score)}</span>
          </div>
          {/* پیش‌نمایش نتیجه گوگل */}
          <div className="rounded-xl border border-line p-3 text-start" dir="rtl">
            <p className="truncate text-[11px] text-muted" dir="ltr">{siteUrl.replace(/^https?:\/\//, "")} › mag › {slug}</p>
            <p className="mt-1 line-clamp-1 text-[15px] text-[#1a0dab]">{fullTitle}</p>
            <p className="mt-1 line-clamp-2 text-xs leading-5 text-ink-soft">{metaDesc}</p>
          </div>
          <Field label="کلمه کلیدی اصلی" error={errors.focusKeyword}>
            <input className="field h-10" maxLength={60} value={f.focusKeyword} onChange={(e) => set("focusKeyword", e.target.value)} />
          </Field>
          <Field label="تگ عنوان (Title)" error={errors.seoTitle} hint={`${faNumber(fullTitle.length)} / ${faNumber(SEO_TITLE_RANGE[1])}`}>
            <input className="field h-10" maxLength={70} placeholder="خالی = عنوان مقاله" value={f.seoTitle} onChange={(e) => set("seoTitle", e.target.value)} />
          </Field>
          <Field label="توضیحات متا" error={errors.seoDescription} hint={`${faNumber((f.seoDescription || f.excerpt).length)} / ${faNumber(SEO_DESC_RANGE[1])}`}>
            <textarea className="field h-24 py-2" maxLength={170} placeholder="خالی = خلاصه مقاله" value={f.seoDescription} onChange={(e) => set("seoDescription", e.target.value)} />
          </Field>
          <div className="grid gap-2">
            <button type="button" className="btn-outline h-10 text-xs" onClick={autoOptimize}>بهینه‌سازی خودکار سئو</button>
            <button
              type="button"
              className="btn-outline h-10 text-xs"
              disabled={!aiEnabled || aiBusy || f.body.length < 50}
              title={aiEnabled ? undefined : "اول در بخش «هوش مصنوعی» کلید API را وارد کنید"}
              onClick={aiSuggest}
            >
              {aiBusy ? "در حال نوشتن پیشنهاد…" : "پیشنهاد سئو و FAQ با هوش مصنوعی"}
            </button>
          </div>
          <ul className="space-y-1.5 text-xs leading-5">
            {seo.checks.map((c, i) => (
              <li key={i} className="flex items-start gap-2">
                <span className={`mt-1.5 size-2 shrink-0 rounded-full ${STATUS_STYLE[c.status]}`} aria-hidden />
                <span className={c.status === "good" ? "text-muted" : ""}>{c.label}</span>
              </li>
            ))}
          </ul>
        </section>
      </aside>
    </div>
  );
}
