import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import { PageHero } from "@/components/site/page-hero";
import { Reveal } from "@/components/site/motion";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { db } from "@/lib/db";
import { Calendar, User, ArrowLeft, ArrowRight, Tag } from "lucide-react";

export const revalidate = 60;

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const p = await db.blogPost.findUnique({ where: { slug } });
  if (!p) return { title: "Article Not Found" };
  return {
    title: p.metaTitle || p.title,
    description: p.metaDescription || p.excerpt,
    alternates: { canonical: `/blog/${p.slug}` },
    openGraph: { title: p.title, description: p.excerpt, type: "article" },
  };
}

export default async function BlogDetailPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await db.blogPost.findUnique({ where: { slug } });
  if (!post || !post.isPublished) notFound();

  const tags = JSON.parse(post.tags || "[]") as string[];
  const related = await db.blogPost.findMany({
    where: { isPublished: true, slug: { not: post.slug }, ...(post.category ? { category: post.category } : {}) },
    take: 3,
    orderBy: { publishedAt: "desc" },
  });
  const fallbacks = ["/uploads/project-chiller.jpg", "/uploads/project-coldstorage.jpg", "/uploads/project-hospital.jpg"];

  return (
    <>
      <PageHero
        eyebrow={post.category || "Article"}
        title={post.title}
        subtitle={post.excerpt}
        breadcrumbs={[{ label: "Blog", href: "/blog" }, { label: post.title }]}
      />

      <article className="py-16 lg:py-24">
        <div className="container-mx max-w-3xl">
          <Reveal>
            <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground mb-8 pb-8 border-b border-border">
              <span className="flex items-center gap-1.5"><User className="size-4" /> {post.authorName || "AHE Engineering Team"}</span>
              {post.publishedAt && <span className="flex items-center gap-1.5"><Calendar className="size-4" /> {new Date(post.publishedAt).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}</span>}
            </div>
          </Reveal>

          {post.featuredImage && (
            <Reveal>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={post.featuredImage} alt={post.title} className="w-full aspect-[16/9] object-cover rounded-2xl mb-10 border border-border" />
            </Reveal>
          )}

          <Reveal>
            <div className="prose prose-lg max-w-none">
              {post.content.split("\n").map((line, i) => {
                if (line.startsWith("## ")) return <h2 key={i} className="text-2xl font-bold text-foreground mt-8 mb-4">{line.slice(3)}</h2>;
                if (line.startsWith("# ")) return <h1 key={i} className="text-3xl font-bold text-foreground mt-8 mb-4">{line.slice(2)}</h1>;
                if (line.startsWith("- ")) return <li key={i} className="text-muted-foreground ml-6">{line.slice(2)}</li>;
                if (!line.trim()) return null;
                return <p key={i} className="text-muted-foreground leading-relaxed mb-4">{line}</p>;
              })}
            </div>
          </Reveal>

          {tags.length > 0 && (
            <Reveal>
              <div className="mt-10 pt-8 border-t border-border flex flex-wrap items-center gap-2">
                <Tag className="size-4 text-muted-foreground mr-1" />
                {tags.map((t) => (
                  <span key={t} className="px-3 py-1 rounded-full bg-muted text-muted-foreground text-sm">#{t}</span>
                ))}
              </div>
            </Reveal>
          )}

          <Reveal>
            <Card className="mt-10 p-8 rounded-2xl brand-gradient text-white text-center">
              <h3 className="text-xl font-bold text-white">Need Expert HVAC Help?</h3>
              <p className="mt-1.5 text-white/85 text-sm">Our engineers are ready to assess your facility and recommend the right solution.</p>
              <Button asChild className="mt-5 bg-white text-[var(--brand-royal)] hover:bg-white/90">
                <Link href="/contact">Get a Free Quote <ArrowRight className="size-4" /></Link>
              </Button>
            </Card>
          </Reveal>
        </div>
      </article>

      {related.length > 0 && (
        <section className="py-16 bg-muted/30 border-t border-border">
          <div className="container-mx">
            <h2 className="text-2xl font-extrabold mb-8">Related Articles</h2>
            <div className="grid sm:grid-cols-3 gap-6">
              {related.map((p, i) => (
                <Link key={p.id} href={`/blog/${p.slug}`} className="group">
                  <Card className="overflow-hidden rounded-2xl h-full hover:shadow-brand transition-shadow">
                    <div className="aspect-[16/10] overflow-hidden">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img src={p.featuredImage || fallbacks[i % 3]} alt={p.title} className="size-full object-cover group-hover:scale-105 transition-transform" />
                    </div>
                    <div className="p-4">
                      <div className="text-xs text-muted-foreground mb-1">{p.category}</div>
                      <h3 className="font-bold leading-snug line-clamp-2 group-hover:text-[var(--brand-royal)] transition-colors">{p.title}</h3>
                    </div>
                  </Card>
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}

      <div className="container-mx py-10">
        <Link href="/blog" className="inline-flex items-center gap-1.5 text-sm font-semibold text-[var(--brand-royal)]">
          <ArrowLeft className="size-4" /> Back to All Articles
        </Link>
      </div>
    </>
  );
}
