import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import {
  fetchAdminPosts, savePost, deletePost, uploadImage, type BlogPost,
} from "@/lib/api";
import { Plus, Trash2, Upload, Save, X } from "lucide-react";

export const Route = createFileRoute("/admin/blog")({
  head: () => ({ meta: [{ title: "Admin · Blog" }, { name: "robots", content: "noindex" }] }),
  component: AdminBlog,
});

const empty: Partial<BlogPost> = {
  slug: "", title: "", excerpt: "", cover_image_url: "", body_md: "", published: false,
};

function AdminBlog() {
  const [items, setItems] = useState<BlogPost[]>([]);
  const [editing, setEditing] = useState<Partial<BlogPost> | null>(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  async function reload() {
    try { setItems(await fetchAdminPosts()); }
    catch (e) { setErr(e instanceof Error ? e.message : "Failed to load"); }
  }
  useEffect(() => { reload(); }, []);

  async function onSave() {
    if (!editing) return;
    setBusy(true); setErr(null);
    try {
      await savePost(editing.id ?? null, editing);
      setEditing(null);
      await reload();
    } catch (e) { setErr(e instanceof Error ? e.message : "Save failed"); }
    finally { setBusy(false); }
  }
  async function onDelete(id: number) {
    if (!confirm("Delete this post?")) return;
    await deletePost(id); reload();
  }
  async function onFile(f: File | null) {
    if (!f || !editing) return;
    setBusy(true);
    try {
      const url = await uploadImage(f);
      setEditing({ ...editing, cover_image_url: url });
    } catch (e) { setErr(e instanceof Error ? e.message : "Upload failed"); }
    finally { setBusy(false); }
  }

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <h1 className="font-display text-2xl font-bold">Blog posts</h1>
        <button onClick={() => setEditing({ ...empty })}
          className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground">
          <Plus className="h-4 w-4" /> New post
        </button>
      </div>

      {err && <p className="mb-4 rounded bg-red-50 p-3 text-sm text-red-700">{err}</p>}

      <div className="overflow-hidden rounded-xl border bg-white">
        <table className="w-full text-sm">
          <thead className="bg-slate-50 text-left">
            <tr>
              <th className="p-3">Title</th><th className="p-3">Status</th>
              <th className="p-3">Updated</th><th className="p-3"></th>
            </tr>
          </thead>
          <tbody>
            {items.map((p) => (
              <tr key={p.id} className="border-t">
                <td className="p-3 font-medium">{p.title}</td>
                <td className="p-3">
                  <span className={`rounded-full px-2 py-0.5 text-xs ${p.published ? "bg-emerald-100 text-emerald-700" : "bg-slate-100 text-slate-600"}`}>
                    {p.published ? "Published" : "Draft"}
                  </span>
                </td>
                <td className="p-3 text-muted-foreground">{p.updated_at?.slice(0, 10)}</td>
                <td className="p-3 text-right">
                  <button onClick={() => setEditing(p)} className="mr-2 rounded border px-3 py-1 text-xs hover:bg-slate-50">Edit</button>
                  <button onClick={() => onDelete(p.id)} className="rounded border border-red-200 px-3 py-1 text-xs text-red-600 hover:bg-red-50">
                    <Trash2 className="inline h-3 w-3" />
                  </button>
                </td>
              </tr>
            ))}
            {items.length === 0 && (
              <tr><td colSpan={4} className="p-6 text-center text-muted-foreground">No posts yet.</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {editing && (
        <div className="fixed inset-0 z-50 grid place-items-center bg-black/40 p-4" onClick={() => setEditing(null)}>
          <div className="w-full max-w-3xl rounded-2xl bg-white p-6 shadow-xl" onClick={(e) => e.stopPropagation()}>
            <div className="mb-4 flex items-center justify-between">
              <h2 className="font-display text-xl font-bold">{editing.id ? "Edit post" : "New post"}</h2>
              <button onClick={() => setEditing(null)}><X className="h-5 w-5" /></button>
            </div>

            <div className="grid gap-3">
              <label className="block">
                <span className="mb-1 block text-xs font-medium text-foreground/70">Title</span>
                <input value={editing.title ?? ""} onChange={(e) => setEditing({ ...editing, title: e.target.value })} className="w-full rounded border px-3 py-2 text-sm" />
              </label>
              <label className="block">
                <span className="mb-1 block text-xs font-medium text-foreground/70">Slug</span>
                <input value={editing.slug ?? ""} onChange={(e) => setEditing({ ...editing, slug: e.target.value })} placeholder="auto from title" className="w-full rounded border px-3 py-2 text-sm" />
              </label>
              <label className="block">
                <span className="mb-1 block text-xs font-medium text-foreground/70">Excerpt</span>
                <textarea rows={2} value={editing.excerpt ?? ""} onChange={(e) => setEditing({ ...editing, excerpt: e.target.value })} className="w-full rounded border px-3 py-2 text-sm" />
              </label>
              <label className="block">
                <span className="mb-1 block text-xs font-medium text-foreground/70">Cover image</span>
                <div className="flex items-center gap-3">
                  {editing.cover_image_url && <img src={editing.cover_image_url} alt="" className="h-16 w-24 rounded object-cover" />}
                  <input value={editing.cover_image_url ?? ""} onChange={(e) => setEditing({ ...editing, cover_image_url: e.target.value })} placeholder="Image URL" className="flex-1 rounded border px-3 py-2 text-sm" />
                  <label className="inline-flex cursor-pointer items-center gap-1 rounded border px-3 py-2 text-sm hover:bg-slate-50">
                    <Upload className="h-4 w-4" /> Upload
                    <input type="file" accept="image/*" className="hidden" onChange={(e) => onFile(e.target.files?.[0] ?? null)} />
                  </label>
                </div>
              </label>
              <label className="block">
                <span className="mb-1 block text-xs font-medium text-foreground/70">Body</span>
                <textarea rows={12} value={editing.body_md ?? ""} onChange={(e) => setEditing({ ...editing, body_md: e.target.value })} className="w-full rounded border px-3 py-2 font-mono text-sm" />
              </label>
              <label className="inline-flex items-center gap-2 text-sm">
                <input type="checkbox" checked={!!editing.published} onChange={(e) => setEditing({ ...editing, published: e.target.checked })} />
                Published
              </label>
            </div>

            <div className="mt-6 flex justify-end gap-2">
              <button onClick={() => setEditing(null)} className="rounded border px-4 py-2 text-sm">Cancel</button>
              <button onClick={onSave} disabled={busy}
                className="inline-flex items-center gap-2 rounded bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground disabled:opacity-60">
                <Save className="h-4 w-4" /> {busy ? "Saving…" : "Save"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
