import Link from "next/link";
import { db } from "@/lib/db";
import { AdminPageHeader } from "@/components/admin/page-header";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Plus, Pencil, ImageIcon } from "lucide-react";

export const dynamic = "force-dynamic";

export default async function AdminBlogPage() {
  const posts = await db.blogPost.findMany({ orderBy: { createdAt: "desc" } });

  return (
    <>
      <AdminPageHeader title="Blog" description={`${posts.length} posts configured`}>
        <Button asChild className="brand-gradient text-white">
          <Link href="/admin/blog/new"><Plus className="size-4 mr-1.5" /> Add Post</Link>
        </Button>
      </AdminPageHeader>

      <Card className="rounded-2xl overflow-hidden">
        <div className="divide-y divide-border">
          {posts.map((p) => (
            <div key={p.id} className="flex items-center gap-4 p-4 hover:bg-accent/40 transition-colors">
              <div className="size-14 rounded-lg overflow-hidden border border-border shrink-0 bg-muted">
                {p.featuredImage ? (
                  <img src={p.featuredImage} alt={p.title} className="size-full object-cover" />
                ) : (
                  <div className="size-full grid place-items-center text-muted-foreground">
                    <ImageIcon className="size-5" />
                  </div>
                )}
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="font-semibold truncate">{p.title}</span>
                  {p.isPublished ? (
                    <Badge className="brand-gradient text-white text-xs">Published</Badge>
                  ) : (
                    <Badge variant="outline" className="text-xs text-muted-foreground">Draft</Badge>
                  )}
                  {p.category && <Badge variant="secondary" className="text-xs">{p.category}</Badge>}
                </div>
                <div className="text-xs text-muted-foreground truncate mt-0.5">
                  /{p.slug}
                  {p.publishedAt && <span className="ml-2">· Published {new Date(p.publishedAt).toLocaleDateString()}</span>}
                  {p.authorName && <span className="ml-2">· by {p.authorName}</span>}
                </div>
              </div>
              <Button asChild variant="outline" size="sm">
                <Link href={`/admin/blog/edit/${p.id}`}><Pencil className="size-3.5 mr-1" /> Edit</Link>
              </Button>
            </div>
          ))}
          {posts.length === 0 && (
            <div className="p-12 text-center text-muted-foreground">No blog posts yet. Click &quot;Add Post&quot; to create one.</div>
          )}
        </div>
      </Card>
    </>
  );
}
