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 { MapPin, Calendar, Building2, Tag, ArrowRight, ArrowLeft } 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.project.findUnique({ where: { slug } });
  if (!p) return { title: "Project Not Found" };
  return {
    title: p.metaTitle || p.title,
    description: p.metaDescription || p.description,
    alternates: { canonical: `/projects/${p.slug}` },
    openGraph: { title: p.title, description: p.description },
  };
}

export default async function ProjectDetailPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const project = await db.project.findUnique({ where: { slug } });
  if (!project || !project.isEnabled) notFound();

  const images = JSON.parse(project.images || "[]") as string[];
  const videos = JSON.parse(project.videos || "[]") as string[];
  const fallbacks = ["/uploads/project-chiller.jpg", "/uploads/project-coldstorage.jpg", "/uploads/project-hospital.jpg", "/uploads/hero-hvac.jpg"];
  const cover = images[0] || fallbacks[0];

  const meta = [
    { icon: Tag, label: "Category", value: project.category },
    { icon: MapPin, label: "Location", value: project.location || "Karachi, Pakistan" },
    { icon: Calendar, label: "Completed", value: project.completionDate ? new Date(project.completionDate).toLocaleDateString("en-US", { year: "numeric", month: "long" }) : "—" },
    { icon: Building2, label: "Client", value: project.client || "Confidential" },
  ];

  return (
    <>
      <PageHero
        eyebrow={project.category}
        title={project.title}
        subtitle={project.description}
        breadcrumbs={[{ label: "Projects", href: "/projects" }, { label: project.title }]}
      />

      <section className="py-16 lg:py-24">
        <div className="container-mx">
          {/* Cover */}
          <Reveal>
            <div className="relative rounded-3xl overflow-hidden shadow-brand mb-10">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={cover} alt={project.title} className="w-full aspect-[21/9] object-cover" />
            </div>
          </Reveal>

          <div className="grid lg:grid-cols-3 gap-10">
            <div className="lg:col-span-2">
              {/* Meta grid */}
              <Reveal>
                <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-10">
                  {meta.map((m) => (
                    <Card key={m.label} className="p-4 rounded-xl">
                      <div className="flex items-center gap-2 text-xs text-muted-foreground uppercase tracking-wide">
                        <m.icon className="size-3.5" /> {m.label}
                      </div>
                      <div className="mt-1.5 font-semibold text-foreground text-sm">{m.value}</div>
                    </Card>
                  ))}
                </div>
              </Reveal>

              <Reveal>
                <h2 className="text-2xl font-extrabold mb-4">Project Overview</h2>
                <div className="prose prose-lg max-w-none [&_p]:text-muted-foreground leading-relaxed">
                  {project.content.split("\n").map((p, i) => p.trim() ? <p key={i} className="mb-4">{p}</p> : null)}
                </div>
              </Reveal>

              {/* Gallery */}
              {images.length > 0 && (
                <Reveal delay={0.1}>
                  <h3 className="mt-12 mb-5 text-xl font-bold">Project Gallery</h3>
                  <div className="grid sm:grid-cols-2 gap-4">
                    {images.map((img, i) => (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img key={i} src={img} alt={`${project.title} ${i + 1}`} className="w-full aspect-[4/3] object-cover rounded-xl border border-border" />
                    ))}
                  </div>
                </Reveal>
              )}

              {/* Videos */}
              {videos.length > 0 && (
                <Reveal delay={0.15}>
                  <h3 className="mt-12 mb-5 text-xl font-bold">Project Videos</h3>
                  <div className="grid sm:grid-cols-2 gap-4">
                    {videos.map((v, i) => (
                      <video key={i} src={v} controls className="w-full rounded-xl border border-border" />
                    ))}
                  </div>
                </Reveal>
              )}
            </div>

            {/* Sidebar */}
            <div className="lg:col-span-1">
              <div className="sticky top-28 space-y-5">
                <Card className="p-6 rounded-2xl brand-gradient text-white">
                  <h3 className="font-bold text-lg text-white">Start a Similar Project</h3>
                  <p className="mt-1.5 text-sm text-white/80">Tell us about your requirements and get a free engineering assessment.</p>
                  <Button asChild className="mt-4 w-full bg-white text-[var(--brand-royal)] hover:bg-white/90">
                    <Link href="/contact">Request Quote <ArrowRight className="size-4" /></Link>
                  </Button>
                </Card>
                <Link href="/projects" className="inline-flex items-center gap-1.5 text-sm font-semibold text-[var(--brand-royal)]">
                  <ArrowLeft className="size-3.5" /> Back to All Projects
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
