"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import {
  createArticleAction,
  updateArticleAction,
  publishArticleAction,
  unpublishArticleAction,
  deleteArticleAction,
} from "./_actions";

export type CategoryOpt = { id: string; slug: string; name: string };

export type ArticleFormProps = {
  mode: "create" | "edit";
  article?: {
    id: string;
    slug: string;
    title: string;
    excerpt: string | null;
    content: string;
    coverImage: string | null;
    status: string;
    publishedAt: Date | null;
    scheduledFor: Date | null;
    metaTitle: string | null;
    metaDesc: string | null;
    metaKeywords: string | null;
    focusKeyword: string | null;
    canonicalUrl: string | null;
    noIndex: boolean;
    seoScore: number;
    readabilityScore: number;
    categorySlug: string | null;
    tags: string[];
    featured: boolean;
    pinned: boolean;
    pinOrder: number;
  };
  categories: CategoryOpt[];
};

function toLocalDateTimeInput(d: Date | null): string {
  if (!d) return "";
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

export function ArticleForm({ mode, article, categories }: ArticleFormProps) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const [showSeo, setShowSeo] = useState(false);

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    const fd = new FormData(e.currentTarget);
    startTransition(async () => {
      try {
        if (mode === "create") {
          const res = await createArticleAction(fd);
          if (res && "ok" in res && res.ok === false) {
            setError(res.error);
          }
          // success → redirect handled by server action
        } else if (article) {
          const res = await updateArticleAction(article.id, fd);
          if (res.ok === false) {
            setError(res.error);
          } else {
            router.refresh();
          }
        }
      } catch (err) {
        // redirect() throws NEXT_REDIRECT on success → ignore
        const msg = err instanceof Error ? err.message : String(err);
        if (!msg.includes("NEXT_REDIRECT")) setError(msg);
      }
    });
  }

  async function quickAction(fn: () => Promise<{ ok: boolean; error?: string }>) {
    setError(null);
    startTransition(async () => {
      try {
        const res = await fn();
        if (!res.ok) setError(res.error ?? "Lỗi");
        else router.refresh();
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        if (!msg.includes("NEXT_REDIRECT")) setError(msg);
      }
    });
  }

  const a = article;

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && (
        <div className="rounded-lg border border-rose-500/40 bg-rose-500/10 px-4 py-3 text-sm text-rose-300">
          {error}
        </div>
      )}

      <div className="grid lg:grid-cols-[1fr_320px] gap-6">
        {/* Main column */}
        <div className="space-y-5">
          <div>
            <label className="text-xs font-medium text-ink-muted block mb-1.5">Tiêu đề *</label>
            <input
              name="title"
              required
              defaultValue={a?.title ?? ""}
              className="w-full px-3 py-2.5 rounded-lg bg-bg-elevated border border-stroke-subtle text-base focus:outline-none focus:border-accent-primary"
              placeholder="VD: Bitcoin tăng mạnh, vượt 100K USD"
            />
          </div>

          <div>
            <label className="text-xs font-medium text-ink-muted block mb-1.5">
              Slug <span className="text-ink-muted/60">(tự sinh nếu để trống)</span>
            </label>
            <input
              name="slug"
              defaultValue={a?.slug ?? ""}
              className="w-full px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm font-mono focus:outline-none focus:border-accent-primary"
              placeholder="bitcoin-tang-manh-vuot-100k"
            />
          </div>

          <div>
            <label className="text-xs font-medium text-ink-muted block mb-1.5">
              Tóm tắt <span className="text-ink-muted/60">(excerpt)</span>
            </label>
            <textarea
              name="excerpt"
              rows={2}
              defaultValue={a?.excerpt ?? ""}
              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"
              placeholder="2-3 câu mở đầu, để trống sẽ tự rút gọn từ nội dung."
            />
          </div>

          <div>
            <label className="text-xs font-medium text-ink-muted block mb-1.5">
              Nội dung * <span className="text-ink-muted/60">(Markdown)</span>
            </label>
            <textarea
              name="content"
              required
              rows={20}
              defaultValue={a?.content ?? ""}
              className="w-full px-3 py-2.5 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm font-mono leading-relaxed focus:outline-none focus:border-accent-primary"
              placeholder={"# Tiêu đề con\n\nNội dung markdown ở đây…"}
            />
          </div>

          {/* SEO collapsible */}
          <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 overflow-hidden">
            <button
              type="button"
              onClick={() => setShowSeo(!showSeo)}
              className="w-full flex items-center justify-between px-4 py-3 text-sm font-medium hover:bg-bg-elevated/60 transition"
            >
              <span>
                Tinh chỉnh SEO
                {a && (
                  <span className="ml-2 text-xs text-ink-muted">
                    Score: <span className={a.seoScore >= 70 ? "text-emerald-300" : a.seoScore >= 50 ? "text-amber-300" : "text-rose-300"}>{a.seoScore}</span>
                    {" · "}Readability: <span className={a.readabilityScore >= 60 ? "text-emerald-300" : "text-amber-300"}>{a.readabilityScore}</span>
                  </span>
                )}
              </span>
              <span className="text-ink-muted">{showSeo ? "−" : "+"}</span>
            </button>
            {showSeo && (
              <div className="px-4 pb-4 space-y-3">
                <div>
                  <label className="text-xs font-medium text-ink-muted block mb-1">Focus keyword</label>
                  <input
                    name="focusKeyword"
                    defaultValue={a?.focusKeyword ?? ""}
                    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"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-ink-muted block mb-1">Meta title</label>
                  <input
                    name="metaTitle"
                    defaultValue={a?.metaTitle ?? ""}
                    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"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-ink-muted block mb-1">Meta description</label>
                  <textarea
                    name="metaDesc"
                    rows={2}
                    defaultValue={a?.metaDesc ?? ""}
                    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"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-ink-muted block mb-1">Meta keywords</label>
                  <input
                    name="metaKeywords"
                    defaultValue={a?.metaKeywords ?? ""}
                    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"
                    placeholder="bitcoin, btc, crypto"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-ink-muted block mb-1">Canonical URL</label>
                  <input
                    name="canonicalUrl"
                    type="url"
                    defaultValue={a?.canonicalUrl ?? ""}
                    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"
                  />
                </div>
                <label className="flex items-center gap-2 text-sm">
                  <input type="checkbox" name="noIndex" defaultChecked={a?.noIndex ?? false} />
                  <span>Không cho index (noindex)</span>
                </label>
              </div>
            )}
          </div>
        </div>

        {/* Sidebar */}
        <aside className="space-y-4">
          <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4 space-y-3">
            <div>
              <label className="text-xs font-medium text-ink-muted block mb-1.5">Trạng thái</label>
              <select
                name="status"
                defaultValue={a?.status ?? "draft"}
                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"
              >
                <option value="draft">Nháp</option>
                <option value="published">Đã đăng</option>
                <option value="scheduled">Hẹn giờ</option>
                <option value="archived">Lưu trữ</option>
              </select>
            </div>

            <div>
              <label className="text-xs font-medium text-ink-muted block mb-1.5">Hẹn giờ đăng</label>
              <input
                name="scheduledFor"
                type="datetime-local"
                defaultValue={toLocalDateTimeInput(a?.scheduledFor ?? null)}
                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"
              />
            </div>

            <div>
              <label className="text-xs font-medium text-ink-muted block mb-1.5">Đã đăng vào</label>
              <input
                name="publishedAt"
                type="datetime-local"
                defaultValue={toLocalDateTimeInput(a?.publishedAt ?? null)}
                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"
              />
            </div>

            <button
              type="submit"
              disabled={pending}
              className="w-full px-4 py-2.5 rounded-lg bg-accent-primary text-white text-sm font-medium hover:bg-accent-primary/90 disabled:opacity-50 transition"
            >
              {pending ? "Đang lưu…" : mode === "create" ? "Tạo bài" : "Lưu thay đổi"}
            </button>

            {a && (
              <div className="pt-2 border-t border-stroke-subtle space-y-2">
                {a.status === "published" ? (
                  <button
                    type="button"
                    onClick={() => quickAction(() => unpublishArticleAction(a.id))}
                    disabled={pending}
                    className="w-full px-3 py-2 rounded-lg border border-stroke-subtle text-sm hover:bg-bg-elevated/60 disabled:opacity-50 transition"
                  >
                    Gỡ xuất bản
                  </button>
                ) : (
                  <button
                    type="button"
                    onClick={() => quickAction(() => publishArticleAction(a.id))}
                    disabled={pending}
                    className="w-full px-3 py-2 rounded-lg bg-emerald-500/15 border border-emerald-500/30 text-emerald-300 text-sm hover:bg-emerald-500/25 disabled:opacity-50 transition"
                  >
                    Xuất bản ngay
                  </button>
                )}
                <button
                  type="button"
                  onClick={() => {
                    if (confirm(`Xóa "${a.title}"? Không thể khôi phục.`)) {
                      quickAction(() => deleteArticleAction(a.id));
                    }
                  }}
                  disabled={pending}
                  className="w-full px-3 py-2 rounded-lg text-rose-300 text-sm hover:bg-rose-500/10 disabled:opacity-50 transition"
                >
                  Xóa bài
                </button>
              </div>
            )}
          </div>

          <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4 space-y-3">
            <div>
              <label className="text-xs font-medium text-ink-muted block mb-1.5">Chuyên mục</label>
              <select
                name="categorySlug"
                defaultValue={a?.categorySlug ?? ""}
                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"
              >
                <option value="">— Chưa phân loại —</option>
                {categories.map((c) => (
                  <option key={c.id} value={c.slug}>
                    {c.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="text-xs font-medium text-ink-muted block mb-1.5">
                Tags <span className="text-ink-muted/60">(phẩy ngăn cách)</span>
              </label>
              <input
                name="tags"
                defaultValue={a?.tags.join(", ") ?? ""}
                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"
                placeholder="bitcoin, vn-index, fed"
              />
            </div>

            <div>
              <label className="text-xs font-medium text-ink-muted block mb-1.5">Ảnh đại diện</label>
              <input
                name="coverImage"
                type="url"
                defaultValue={a?.coverImage ?? ""}
                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"
                placeholder="https://…/cover.jpg"
              />
              {a?.coverImage && (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={a.coverImage}
                  alt=""
                  className="mt-2 w-full aspect-video object-cover rounded-lg border border-stroke-subtle"
                />
              )}
            </div>
          </div>

          {/* Promotion */}
          <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4 space-y-3">
            <div className="text-xs font-medium text-ink-muted uppercase tracking-wider">
              Quảng bá
            </div>
            <label className="flex items-start gap-2 text-sm">
              <input
                type="checkbox"
                name="featured"
                defaultChecked={a?.featured ?? false}
                className="mt-0.5"
              />
              <span>
                <span className="block">Bài nổi bật (hero homepage)</span>
                <span className="block text-xs text-ink-muted">
                  Hiển thị to ở đầu trang chủ. Bài mới được đánh featured sẽ thay thế bài cũ.
                </span>
              </span>
            </label>
            <label className="flex items-start gap-2 text-sm">
              <input
                type="checkbox"
                name="pinned"
                defaultChecked={a?.pinned ?? false}
                className="mt-0.5"
              />
              <span>
                <span className="block">Ghim (lên đầu chuyên mục/tag)</span>
                <span className="block text-xs text-ink-muted">
                  Bài ghim sẽ luôn xuất hiện trước bài thường khi liệt kê.
                </span>
              </span>
            </label>
            <div>
              <label className="text-xs font-medium text-ink-muted block mb-1.5">
                Thứ tự ghim (số nhỏ lên trước)
              </label>
              <input
                name="pinOrder"
                type="number"
                defaultValue={a?.pinOrder ?? 0}
                min={0}
                max={999}
                className="w-32 px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
              />
            </div>
          </div>
        </aside>
      </div>
    </form>
  );
}
