"use client";

import { useState } from "react";

type Draft = {
  title: string;
  slug: string;
  excerpt: string;
  body: string;
  cover_url: string;
  status: "draft" | "published";
};

export function BlogEditor({
  postId,
  initial,
}: {
  postId?: string;
  initial?: Partial<Draft>;
}) {
  const [draft, setDraft] = useState<Draft>({
    title: initial?.title || "",
    slug: initial?.slug || "",
    excerpt: initial?.excerpt || "",
    body: initial?.body || "",
    cover_url: initial?.cover_url || "",
    status: initial?.status || "draft",
  });
  const [msg, setMsg] = useState("");
  const [pending, setPending] = useState(false);

  async function save(status: "draft" | "published") {
    setPending(true);
    setMsg("");
    const payload = { ...draft, status };
    const res = await fetch(postId ? `/api/admin/blog/${postId}` : "/api/admin/blog", {
      method: postId ? "PUT" : "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    const json = await res.json();
    setPending(false);
    if (!res.ok) {
      setMsg(json.error || "Save failed");
      return;
    }
    if (!postId && json.post?.id) {
      window.location.href = `/admin/blog/${json.post.id}`;
      return;
    }
    setDraft((d) => ({ ...d, slug: json.post.slug, status: json.post.status }));
    setMsg(status === "published" ? "Published." : "Draft saved.");
  }

  return (
    <form
      className="space-y-4"
      onSubmit={(e) => {
        e.preventDefault();
        save(draft.status);
      }}
    >
      <label className="block text-sm">
        Title
        <input
          required
          value={draft.title}
          onChange={(e) => setDraft({ ...draft, title: e.target.value })}
          className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5"
        />
      </label>
      <label className="block text-sm">
        Slug (URL)
        <input
          value={draft.slug}
          placeholder="auto-from-title"
          onChange={(e) => setDraft({ ...draft, slug: e.target.value })}
          className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5 font-mono text-sm"
        />
      </label>
      <label className="block text-sm">
        Excerpt
        <textarea
          value={draft.excerpt}
          onChange={(e) => setDraft({ ...draft, excerpt: e.target.value })}
          rows={3}
          className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5"
        />
      </label>
      <label className="block text-sm">
        Cover image URL
        <input
          value={draft.cover_url}
          onChange={(e) => setDraft({ ...draft, cover_url: e.target.value })}
          placeholder="https://…"
          className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5"
        />
      </label>
      <label className="block text-sm">
        Body
        <span className="mt-0.5 block text-xs text-forest/50">
          Markdown: # headings, **bold**, - lists, [links](https://), images.
        </span>
        <textarea
          value={draft.body}
          onChange={(e) => setDraft({ ...draft, body: e.target.value })}
          rows={18}
          className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5 font-mono text-sm leading-relaxed"
        />
      </label>
      <div className="flex flex-wrap gap-3">
        <button
          type="button"
          disabled={pending}
          onClick={() => save("draft")}
          className="rounded-full border border-forest/20 px-5 py-2.5 text-sm font-semibold disabled:opacity-60"
        >
          Save draft
        </button>
        <button
          type="button"
          disabled={pending}
          onClick={() => save("published")}
          className="rounded-full bg-forest px-5 py-2.5 text-sm font-semibold text-gold-2 disabled:opacity-60"
        >
          Publish
        </button>
        {postId && draft.slug ? (
          <a href={`/blog/${draft.slug}`} className="px-3 py-2.5 text-sm text-terra" target="_blank" rel="noreferrer">
            View post
          </a>
        ) : null}
      </div>
      {msg ? <p className="text-sm text-forest">{msg}</p> : null}
    </form>
  );
}
