import { notFound } from "next/navigation";
import Link from "next/link";
import type { Metadata } from "next";
import { prisma } from "@/lib/db";

export const dynamic = "force-dynamic";

const INCLUSION_ICONS: Record<string, string> = {
  "Visa":        "airplane_ticket",
  "Hotel":       "apartment",
  "Qur'an":      "menu_book",
  "Ustadh":      "mosque",
  "Ziyaarah":    "directions_bus",
  "Transportation": "directions_bus",
};

function iconFor(label: string) {
  return Object.entries(INCLUSION_ICONS).find(([k]) => label.includes(k))?.[1] ?? "check_circle";
}

function formatNaira(n: number) {
  return `₦${n.toLocaleString("en-NG")}`;
}

function formatDate(d: Date) {
  return d.toLocaleDateString("en-NG", { day: "numeric", month: "long", year: "numeric" });
}

interface Props { params: Promise<{ slug: string }> }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  try {
    const pkg = await prisma.tripPackage.findUnique({ where: { slug } });
    if (!pkg) return { title: "Package Not Found" };
    return { title: `${pkg.name} | Al-Bakkah Travels`, description: pkg.description };
  } catch {
    return { title: "Al-Bakkah Travels" };
  }
}

export default async function PackageDetailPage({ params }: Props) {
  const { slug } = await params;
  const now = new Date();

  let pkg;
  try {
    pkg = await prisma.tripPackage.findUnique({
      where: { slug },
      include: {
        offers: {
          where: { isActive: true, validFrom: { lte: now }, validUntil: { gte: now } },
          orderBy: { discountPct: "desc" },
          take: 1,
        },
      },
    });
  } catch {
    notFound();
  }

  if (!pkg || pkg.status !== "PUBLISHED") notFound();

  const offer = pkg.offers[0] ?? null;
  const actualPrice = Number(pkg.totalCost);
  const earlyBirdPrice = offer ? Math.round(actualPrice * (1 - Number(offer.discountPct) / 100)) : null;
  const displayPrice = earlyBirdPrice ?? actualPrice;
  const slotsLeft = pkg.slotsAvailable - pkg.slotsBooked;
  const isLimited = slotsLeft <= 5;
  const isHajj = pkg.type === "HAJJ";

  const FALLBACK_IMAGE =
    "https://lh3.googleusercontent.com/aida-public/AB6AXuB2agrGjpUpMkxVLiSZ3tQJJ5rZVvNj9IhV4umIHodRUvjtGmtzH65BJOfWapcV_wsw212BXXxzv6vJ6Pc-PRB6lSisBYNxM6FFbGlD2yfr8MKYrg8GJr9qE4MVKzYfLup9m_K_xoYuummoLnVvxORC_uLvElDZ0w5FVUHWy9IuwU7KW-W6PdGI0JHuSTsm1r0m8zZwPZC1xBP5-ZOtBU7mT971kJ_LQA4-Qkh0HaJ9Td2LsCP-Df9fILMV6839Hctwr6q_aWJyHqE";

  return (
    <div className="min-h-screen bg-background">
      {/* ── Breadcrumb ── */}
      <div className="pt-24 pb-4 px-margin-mobile border-b border-white/5 bg-glass-bg backdrop-blur-xl">
        <div className="max-w-container-max mx-auto">
          <nav className="flex items-center gap-2 text-sm text-white/30">
            <Link href="/" className="hover:text-gold-accent transition-colors">Home</Link>
            <span className="material-symbols-outlined text-base text-white/15">chevron_right</span>
            <Link href="/packages" className="hover:text-gold-accent transition-colors">Packages</Link>
            <span className="material-symbols-outlined text-base text-white/15">chevron_right</span>
            <span className="text-white/60 font-medium">{pkg.name}</span>
          </nav>
        </div>
      </div>

      <div className="max-w-container-max mx-auto px-margin-mobile py-12">
        <div className="grid lg:grid-cols-3 gap-10">

          {/* ── Left: Main Content ── */}
          <div className="lg:col-span-2 space-y-8">

            {/* Hero image */}
            <div className="relative w-full h-72 md:h-96 rounded-3xl overflow-hidden">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={pkg.coverImage ?? FALLBACK_IMAGE}
                alt={pkg.name}
                referrerPolicy="no-referrer"
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-background/80 via-transparent to-transparent" />
              <div className="absolute top-5 left-5 flex items-center gap-2">
                <span className={`px-4 py-1.5 rounded-full text-xs font-black uppercase tracking-widest ${
                  isHajj ? "bg-primary-container/90 border border-white/15 text-white" : "shimmer-btn text-surface-deep"
                }`}>
                  {isHajj ? "Hajj" : "Umrah"} {pkg.departureDate.getFullYear()}
                </span>
                {offer && (
                  <span className="px-3 py-1.5 rounded-full bg-red-500 text-white font-black text-xs">
                    {Math.round(Number(offer.discountPct))}% Early Bird
                  </span>
                )}
              </div>
              {isLimited && (
                <div className="absolute top-5 right-5">
                  <span className="flex items-center gap-1.5 bg-red-500/80 backdrop-blur-md text-white px-3 py-1.5 rounded-full text-xs font-bold">
                    <span className="w-1.5 h-1.5 rounded-full bg-white animate-pulse" />
                    Only {slotsLeft} Slots Left
                  </span>
                </div>
              )}
            </div>

            {/* Title block */}
            <div className="space-y-3">
              <span className={`inline-block px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest ${
                isHajj ? "bg-primary-container text-white" : "bg-gold-accent/15 text-gold-accent border border-gold-accent/25"
              }`}>
                {pkg.type}
              </span>
              <h1 className="text-white font-black leading-tight" style={{ fontSize: "clamp(28px, 4vw, 44px)", letterSpacing: "-0.03em" }}>
                {pkg.name}
              </h1>
              <div className="flex flex-wrap gap-6 text-sm text-white/40">
                <span className="flex items-center gap-2">
                  <span className="material-symbols-outlined text-gold-accent text-base" style={{ fontVariationSettings: "'FILL' 1" }}>flight_takeoff</span>
                  Departure: <strong className="text-white ml-1">{formatDate(pkg.departureDate)}</strong>
                </span>
                <span className="flex items-center gap-2">
                  <span className="material-symbols-outlined text-gold-accent text-base" style={{ fontVariationSettings: "'FILL' 1" }}>schedule</span>
                  Duration: <strong className="text-white ml-1">{pkg.durationDays} days</strong>
                </span>
                {pkg.returnDate && (
                  <span className="flex items-center gap-2">
                    <span className="material-symbols-outlined text-gold-accent text-base" style={{ fontVariationSettings: "'FILL' 1" }}>flight_land</span>
                    Return: <strong className="text-white ml-1">{formatDate(pkg.returnDate)}</strong>
                  </span>
                )}
              </div>
            </div>

            {/* Early bird banner */}
            {offer && earlyBirdPrice && (
              <div className="flex items-start gap-4 p-5 rounded-2xl bg-gold-accent/8 border border-gold-accent/25">
                <span className="material-symbols-outlined text-gold-accent text-2xl mt-0.5" style={{ fontVariationSettings: "'FILL' 1" }}>local_offer</span>
                <div>
                  <p className="text-gold-accent font-extrabold text-sm">{offer.title}</p>
                  <p className="text-white/60 text-sm mt-0.5">{offer.description}</p>
                  <p className="text-red-400 text-xs font-semibold mt-1">
                    Offer expires {new Date(offer.validUntil).toLocaleDateString("en-NG", { day: "numeric", month: "long", year: "numeric" })}
                  </p>
                </div>
              </div>
            )}

            {/* Description */}
            <div className="glass-card p-8 rounded-3xl">
              <h2 className="text-white font-black text-lg mb-4">Package Overview</h2>
              <p className="text-white/50 leading-[1.9] text-[15px]">{pkg.description}</p>
            </div>

            {/* What's included */}
            {pkg.inclusions.length > 0 && (
              <div className="glass-card p-8 rounded-3xl">
                <h2 className="text-white font-black text-lg mb-6">What&apos;s Included</h2>
                <div className="grid sm:grid-cols-2 gap-4">
                  {pkg.inclusions.map((label) => (
                    <div key={label} className="flex items-center gap-4">
                      <div className="w-10 h-10 rounded-xl bg-gold-accent/10 border border-gold-accent/15 flex items-center justify-center shrink-0">
                        <span className="material-symbols-outlined text-gold-accent text-[18px]" style={{ fontVariationSettings: "'FILL' 1" }}>{iconFor(label)}</span>
                      </div>
                      <span className="text-white/60 text-sm font-medium leading-snug">{label}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Speak to a Specialist */}
            <div className="glass-card p-8 rounded-3xl">
              <h2 className="text-white font-black text-lg mb-6">Speak to a Specialist</h2>
              <div className="grid sm:grid-cols-3 gap-4">
                {[
                  { name: "Abu AbdirRahman", phone: "+234 807 756 2271", tel: "tel:+2348077562271", initials: "AA" },
                  { name: "Abu Ishaaq",      phone: "+234 703 516 5748", tel: "tel:+2347035165748", initials: "AI" },
                  { name: "Abu Yuusuf",      phone: "+234 806 067 8106", tel: "tel:+2348060678106", initials: "AY" },
                ].map(({ name, phone, tel, initials }) => (
                  <a key={name} href={tel}
                    className="flex flex-col items-center gap-3 p-5 rounded-2xl border border-white/8 bg-white/[0.02] hover:border-gold-accent/25 hover:bg-gold-accent/5 transition-all group text-center">
                    <div className="w-12 h-12 rounded-full flex items-center justify-center font-black text-surface-deep text-sm group-hover:scale-110 transition-transform"
                      style={{ background: "linear-gradient(135deg, #FED665, #D4AF37)" }}>
                      {initials}
                    </div>
                    <div>
                      <p className="text-white font-bold text-xs leading-tight">{name}</p>
                      <p className="text-gold-accent text-xs mt-1">{phone}</p>
                    </div>
                  </a>
                ))}
              </div>
            </div>
          </div>

          {/* ── Right: Sticky Booking Card ── */}
          <div className="lg:col-span-1">
            <div className="sticky top-24 glass-card rounded-3xl overflow-hidden border border-gold-accent/15">
              <div className="p-7 border-b border-white/[0.07]">
                {isLimited && (
                  <div className="flex items-center gap-2 mb-4 px-3 py-2 rounded-xl bg-red-500/15 border border-red-500/20">
                    <span className="w-2 h-2 rounded-full bg-red-400 animate-pulse" />
                    <span className="text-red-300 text-xs font-bold">LIMITED — {slotsLeft} spots remaining</span>
                  </div>
                )}
                <p className="text-white/30 text-[10px] uppercase tracking-[0.25em] font-bold mb-1">
                  {offer ? "Early Bird Price" : "Package Price"}
                </p>
                {earlyBirdPrice && (
                  <p className="text-white/35 text-base line-through leading-none mb-1">{formatNaira(actualPrice)}</p>
                )}
                <p className="gold-text-glow font-black text-[36px] leading-none mb-1">{formatNaira(displayPrice)}</p>
                <p className="text-white/25 text-xs">per pilgrim</p>
                {offer && (
                  <p className="text-red-400 text-[11px] font-semibold mt-2">
                    Early bird ends {new Date(offer.validUntil).toLocaleDateString("en-NG", { day: "numeric", month: "short" })}
                  </p>
                )}
                {isHajj && (
                  <div className="mt-4 p-3 rounded-xl bg-gold-accent/8 border border-gold-accent/15">
                    <p className="text-gold-accent text-[11px] font-semibold text-center leading-snug">
                      💡 ~{formatNaira(Math.round(displayPrice / 12))}/month over 12 months
                    </p>
                  </div>
                )}
              </div>

              <div className="p-7 space-y-3 border-b border-white/[0.07]">
                <div className="flex justify-between text-sm">
                  <span className="text-white/40">Departure</span>
                  <span className="text-white font-semibold">{formatDate(pkg.departureDate)}</span>
                </div>
                {pkg.returnDate && (
                  <div className="flex justify-between text-sm">
                    <span className="text-white/40">Return</span>
                    <span className="text-white font-semibold">{formatDate(pkg.returnDate)}</span>
                  </div>
                )}
                <div className="flex justify-between text-sm">
                  <span className="text-white/40">Duration</span>
                  <span className="text-white font-semibold">{pkg.durationDays} days</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-white/40">Type</span>
                  <span className="text-white font-semibold">{pkg.type}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-white/40">Availability</span>
                  <span className="text-gold-accent font-semibold">
                    {isLimited ? `${slotsLeft} slots left` : "Open"}
                  </span>
                </div>
              </div>

              <div className="p-7 space-y-3">
                <Link
                  href={`/register?package=${slug}`}
                  className="shimmer-btn block w-full py-4 rounded-2xl font-black text-surface-deep text-center text-sm uppercase tracking-[0.15em] shadow-[0_8px_32px_rgba(254,214,101,0.25)]"
                >
                  Start Saving Toward This Trip
                </Link>
                <a
                  href="tel:+2348077562271"
                  className="block w-full py-4 rounded-2xl border border-white/12 text-white font-bold text-center text-sm hover:bg-white/5 hover:border-gold-accent/25 transition-all"
                >
                  Talk to an Agent
                </a>
                <Link
                  href="/packages"
                  className="block text-center text-white/30 hover:text-white/60 transition-colors text-xs font-medium pt-1"
                >
                  ← Back to all packages
                </Link>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}
