"use client";

import { useEffect, useState } from "react";

type Post = {
  id: string;
  slug: string;
  title: string;
  status: string;
  updated_at: string;
  published_at: string | null;
};

export default function AdminBlogList() {
  const [posts, setPosts] = useState<Post[]>([]);

  function load() {
    fetch("/api/admin/blog")
      .then((r) => r.json())
      .then((j) => setPosts(j.posts || []));
  }

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

  async function remove(id: string) {
    if (!confirm("Delete this post?")) return;
    await fetch(`/api/admin/blog/${id}`, { method: "DELETE" });
    load();
  }

  return (
    <div className="mx-auto max-w-4xl px-4 py-10">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="font-display text-4xl text-forest">Blog</h1>
          <p className="mt-1 text-sm text-forest/70">Write and publish posts. Drafts stay off the public site.</p>
        </div>
        <a href="/admin/blog/new" className="rounded-full bg-gold px-5 py-2.5 text-sm font-bold text-forest">
          New post
        </a>
      </div>
      <ul className="mt-8 space-y-3">
        {posts.length === 0 ? (
          <li className="rounded-3xl bg-cream p-6 text-sm text-forest/60">No posts yet. Write the first one.</li>
        ) : (
          posts.map((p) => (
            <li key={p.id} className="flex flex-wrap items-center justify-between gap-3 rounded-3xl bg-cream px-5 py-4">
              <div>
                <a href={`/admin/blog/${p.id}`} className="font-medium text-forest hover:text-terra">
                  {p.title}
                </a>
                <p className="text-xs text-forest/55">
                  {p.status} · /blog/{p.slug} · {new Date(p.updated_at).toLocaleString()}
                </p>
              </div>
              <div className="flex gap-3 text-sm">
                {p.status === "published" ? (
                  <a href={`/blog/${p.slug}`} className="text-terra" target="_blank" rel="noreferrer">
                    View
                  </a>
                ) : null}
                <a href={`/admin/blog/${p.id}`} className="text-forest">
                  Edit
                </a>
                <button type="button" onClick={() => remove(p.id)} className="text-terra">
                  Delete
                </button>
              </div>
            </li>
          ))
        )}
      </ul>
    </div>
  );
}
