import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { getBlogPostById } from "@/app/lib/content";
import { deleteBlogPost, updateBlogPost } from "@/app/actions/admin";
import { PageHeader } from "@/app/admin/_components/ui";
import BlogForm from "@/app/admin/_components/BlogForm";

export const metadata: Metadata = {
  title: "Edit blog post",
};

export default async function EditBlogPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const post = await getBlogPostById(id);
  if (!post) notFound();

  const updateAction = updateBlogPost.bind(null, post.id);
  const deleteAction = deleteBlogPost.bind(null, post.id);

  return (
    <div>
      <PageHeader
        title="Edit blog post"
        description={post.title}
        action={
          <Link
            href="/admin/blogs"
            className="text-sm font-semibold text-[#1f3fb8] hover:underline"
          >
            ← Back
          </Link>
        }
      />
      <BlogForm
        action={updateAction}
        submitLabel="Save changes"
        initial={{
          title: post.title,
          category: post.category,
          excerpt: post.excerpt,
          imageUrl: post.imageUrl,
          featured: post.featured,
          sortOrder: post.sortOrder,
          published: post.published,
        }}
      />
      <form action={deleteAction} className="mt-4 max-w-2xl">
        <button
          type="submit"
          className="rounded-full border border-red-200 px-5 py-2.5 text-sm font-semibold text-red-600 hover:bg-red-50"
        >
          Delete post
        </button>
      </form>
    </div>
  );
}
