import type { Metadata } from "next";
import Link from "next/link";
import { PageHero } from "@/components/site/page-hero";
import { Reveal, Stagger, StaggerItem } from "@/components/site/motion";
import { Card } from "@/components/ui/card";
import { db } from "@/lib/db";
import { Calendar, User, ArrowRight, ArrowUpRight } from "lucide-react";

export const metadata: Metadata = {
  title: "Blog & Insights",
  description: "HVAC engineering insights, energy efficiency tips and maintenance guides from the AHE Services team.",
  alternates: { canonical: "/blog" },
};

export const revalidate = 60;

export default async function BlogPage() {
  const posts = await db.blogPost.findMany({
    where: { isPublished: true },
    orderBy: { publishedAt: "desc" },
  });
  const featured = posts[0];
  const rest = posts.slice(1);
  const fallbacks = ["/uploads/project-chiller.jpg", "/uploads/project-coldstorage.jpg", "/uploads/project-hospital.jpg", "/uploads/hero-hvac.jpg"];

  return (
    <>
      <PageHero
        eyebrow="Insights"
        title={<>HVAC Knowledge & <span className="bg-gradient-to-r from-[var(--brand-cyan)] to-[var(--brand-royal-light)] bg-clip-text text-transparent">Engineering Tips</span></>}
        subtitle="Practical insights on energy efficiency, maintenance and industrial cooling — from our engineering team to your facility."
        breadcrumbs={[{ label: "Blog" }]}
      />

      <section className="py-16 lg:py-24">
        <div className="container-mx">
          {posts.length === 0 ? (
            <div className="text-center py-20">
              <p className="text-muted-foreground">No articles published yet. Check back soon.</p>
            </div>
          ) : (
            <>
              {/* Featured */}
              {featured && (
                <Reveal>
                  <Link href={`/blog/${featured.slug}`} className="group block mb-12">
                    <Card className="overflow-hidden rounded-3xl border-border/70 hover:shadow-brand transition-all duration-300 grid md:grid-cols-2 gap-0">
                      <div className="relative aspect-[16/10] md:aspect-auto overflow-hidden">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img src={featured.featuredImage || fallbacks[0]} alt={featured.title} className="size-full object-cover group-hover:scale-105 transition-transform duration-500" />
                        <span className="absolute top-4 left-4 px-3 py-1 rounded-full bg-[var(--brand-royal)] text-white text-xs font-semibold">Featured</span>
                      </div>
                      <div className="p-7 sm:p-10 flex flex-col justify-center">
                        <div className="flex items-center gap-4 text-xs text-muted-foreground mb-3">
                          {featured.category && <span className="px-2.5 py-1 rounded-md bg-[var(--brand-royal)]/10 text-[var(--brand-royal)] font-semibold">{featured.category}</span>}
                          {featured.publishedAt && <span className="flex items-center gap-1.5"><Calendar className="size-3.5" />{new Date(featured.publishedAt).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}</span>}
                        </div>
                        <h2 className="text-2xl sm:text-3xl font-extrabold tracking-tight leading-tight group-hover:text-[var(--brand-royal)] transition-colors text-balance">{featured.title}</h2>
                        <p className="mt-3 text-muted-foreground leading-relaxed line-clamp-3">{featured.excerpt}</p>
                        <span className="mt-5 inline-flex items-center gap-1.5 text-sm font-semibold text-[var(--brand-royal)]">Read Article <ArrowRight className="size-4" /></span>
                      </div>
                    </Card>
                  </Link>
                </Reveal>
              )}

              {/* Rest */}
              <Stagger className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
                {rest.map((p, i) => (
                  <StaggerItem key={p.id}>
                    <Link href={`/blog/${p.slug}`} className="group block h-full">
                      <Card className="overflow-hidden rounded-2xl border-border/70 hover:shadow-brand hover:-translate-y-1 transition-all duration-300 h-full flex flex-col">
                        <div className="relative aspect-[16/10] overflow-hidden">
                          {/* eslint-disable-next-line @next/next/no-img-element */}
                          <img src={p.featuredImage || fallbacks[i % fallbacks.length]} alt={p.title} className="size-full object-cover group-hover:scale-105 transition-transform duration-500" />
                        </div>
                        <div className="p-5 flex-1 flex flex-col">
                          <div className="flex items-center gap-3 text-xs text-muted-foreground mb-2">
                            {p.category && <span className="px-2 py-0.5 rounded bg-muted font-medium">{p.category}</span>}
                            {p.publishedAt && <span>{new Date(p.publishedAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}</span>}
                          </div>
                          <h3 className="font-bold text-lg leading-snug group-hover:text-[var(--brand-royal)] transition-colors line-clamp-2">{p.title}</h3>
                          <p className="mt-2 text-sm text-muted-foreground line-clamp-2 flex-1">{p.excerpt}</p>
                          <div className="mt-4 pt-4 border-t border-border/60 flex items-center justify-between text-xs text-muted-foreground">
                            <span className="flex items-center gap-1.5"><User className="size-3.5" /> {p.authorName || "AHE Team"}</span>
                            <ArrowUpRight className="size-4 group-hover:text-[var(--brand-royal)] transition-colors" />
                          </div>
                        </div>
                      </Card>
                    </Link>
                  </StaggerItem>
                ))}
              </Stagger>
            </>
          )}
        </div>
      </section>
    </>
  );
}
