"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { CartProvider, useCart } from "@/context/CartContext";
import { PageNav } from "@/components/PageNav";
import { ProductCard } from "@/components/ProductCard";
import { ProductModal } from "@/components/ProductModal";
import { CartDrawer } from "@/components/CartDrawer";
import { CheckoutModal } from "@/components/CheckoutModal";
import { OrderTrackerModal } from "@/components/OrderTrackerModal";
import { BulkQuoteModal } from "@/components/BulkQuoteModal";
import { Footer } from "@/components/Footer";
import { WhatsAppButton } from "@/components/WhatsAppButton";
import { LogoMark } from "@/components/Logo";
import { Product, Category } from "@/types";
import {
  BookOpen,
  ArrowRight,
  Flame,
  Star,
  Sparkles,
  FileCheck2,
  ListChecks,
  ChevronRight,
} from "lucide-react";

function CatalogueContent() {
  const { setIsQuoteModalOpen } = useCart();
  const [categories, setCategories] = useState<Category[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      try {
        const [catRes, prodRes] = await Promise.all([
          fetch("/api/categories"),
          fetch("/api/products?sort=newest"),
        ]);
        const catData = await catRes.json();
        const prodData = await prodRes.json();
        if (catData.categories) setCategories(catData.categories);
        if (prodData.products) setProducts(prodData.products);
      } catch (e) {
        console.error(e);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const bestSellers = products.filter((p) => p.isBestSeller).slice(0, 4);

  const productsByCategory = (catId: string) =>
    products.filter((p) => p.categoryId === catId);

  return (
    <div className="min-h-screen flex flex-col bg-slate-100 font-sans text-slate-900">
      <PageNav active="catalogue" />

      {/* Magazine Cover Hero */}
      <section className="relative overflow-hidden bg-gradient-to-br from-slate-900 via-teal-950 to-slate-900 text-white">
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(20,184,166,0.18),transparent_55%)]" />
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-14 lg:py-20 relative z-10 grid lg:grid-cols-12 gap-10 items-center">
          <div className="lg:col-span-7 space-y-5">
            <div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-teal-500/20 border border-teal-400/30 text-teal-200 text-xs font-semibold">
              <BookOpen className="w-4 h-4" /> 2026 Product Catalogue &bull; Edition 01
            </div>
            <h1 className="text-4xl sm:text-6xl font-black tracking-tight leading-[1.05]">
              The Diverse Stationery{" "}
              <span className="bg-gradient-to-r from-teal-300 via-teal-200 to-emerald-200 bg-clip-text text-transparent">
                Collection
              </span>
            </h1>
            <p className="text-slate-300 text-base sm:text-lg max-w-2xl leading-relaxed">
              Browse our full range of school, home, office & business supplies — carefully curated from South Africa&apos;s most trusted brands. Every item is genuine stock, priced in Rands and ready for fast nationwide courier delivery.
            </p>
            <div className="flex flex-wrap gap-3 pt-2">
              <a
                href="#catalogue-index"
                className="px-6 py-3.5 bg-gradient-to-r from-teal-500 to-teal-600 hover:from-teal-600 hover:to-teal-700 text-white font-extrabold rounded-2xl shadow-lg flex items-center gap-2 transition-all"
              >
                <span>Browse Collection</span> <ArrowRight className="w-4 h-4" />
              </a>
              <Link
                href="/price-list"
                className="px-5 py-3.5 bg-white/10 hover:bg-white/20 text-white font-bold rounded-2xl border border-white/20 backdrop-blur-sm transition-all flex items-center gap-2"
              >
                <ListChecks className="w-5 h-5 text-teal-300" /> View Price List
              </Link>
            </div>
          </div>

          <div className="lg:col-span-5">
            <div className="relative rounded-3xl overflow-hidden border border-white/15 shadow-2xl bg-white/5 backdrop-blur-md p-6">
              <div className="bg-white rounded-2xl p-5 flex flex-col items-center text-center">
                <LogoMark className="w-24 h-24" />
                <span className="mt-3 font-black text-xl tracking-tight" style={{ color: "#0E9C8E" }}>
                  DIVERSE<span style={{ color: "#C9B79C" }}> STATIONERY</span>
                </span>
                <span className="text-[11px] font-bold text-slate-500 tracking-widest uppercase mt-1">
                  Product Catalogue 2026
                </span>
                <div className="w-full grid grid-cols-3 gap-2 mt-5">
                  <div className="bg-slate-50 rounded-xl py-3 border border-slate-100">
                    <div className="text-xl font-black text-teal-600">{categories.length || 8}</div>
                    <div className="text-[10px] font-bold text-slate-500 uppercase">Categories</div>
                  </div>
                  <div className="bg-slate-50 rounded-xl py-3 border border-slate-100">
                    <div className="text-xl font-black text-teal-600">300+</div>
                    <div className="text-[10px] font-bold text-slate-500 uppercase">Products</div>
                  </div>
                  <div className="bg-slate-50 rounded-xl py-3 border border-slate-100">
                    <div className="text-xl font-black text-teal-600">11</div>
                    <div className="text-[10px] font-bold text-slate-500 uppercase">Brands</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Table of Contents / Category Index */}
      <section id="catalogue-index" className="py-12 bg-white border-b border-slate-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center gap-3 mb-6">
            <span className="text-teal-600 font-black text-sm">01</span>
            <h2 className="text-xl sm:text-2xl font-extrabold text-slate-900">Catalogue Index</h2>
            <div className="flex-1 h-px bg-slate-200" />
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
            {categories.map((cat, i) => (
              <a
                key={cat.id}
                href={`#cat-${cat.id}`}
                className="group flex items-center justify-between p-4 rounded-2xl border border-slate-200 hover:border-teal-500 hover:bg-teal-50/40 transition-all"
              >
                <div className="flex items-center gap-3">
                  <span className="text-xs font-black text-slate-400 group-hover:text-teal-600">
                    {String(i + 1).padStart(2, "0")}
                  </span>
                  <div>
                    <div className="font-bold text-sm text-slate-900 group-hover:text-teal-700">{cat.name}</div>
                    <div className="text-[11px] text-slate-500">{cat.itemCount}+ items</div>
                  </div>
                </div>
                <ChevronRight className="w-4 h-4 text-slate-300 group-hover:text-teal-600 group-hover:translate-x-1 transition-all" />
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* Editor's Picks / Best Sellers Feature */}
      {bestSellers.length > 0 && (
        <section className="py-12 bg-slate-900 text-white">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center gap-2 mb-2">
              <Flame className="w-5 h-5 text-amber-400 fill-amber-500" />
              <span className="text-xs font-black uppercase tracking-wider text-amber-400">Editor&apos;s Picks</span>
            </div>
            <h2 className="text-2xl sm:text-3xl font-black mb-8">Best-Selling Essentials This Season</h2>
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
              {bestSellers.map((p) => (
                <ProductCard key={p.id} product={p} />
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Full Catalogue by Category */}
      <div className="py-4">
        {loading ? (
          <div className="max-w-7xl mx-auto px-4 py-16 text-center text-slate-500 font-semibold animate-pulse">
            Loading catalogue…
          </div>
        ) : (
          categories.map((cat, idx) => {
            const catProducts = productsByCategory(cat.id);
            if (catProducts.length === 0) return null;
            return (
              <section
                key={cat.id}
                id={`cat-${cat.id}`}
                className="py-12 border-b border-slate-200 scroll-mt-24"
              >
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                  {/* Category Banner */}
                  <div className="relative rounded-3xl overflow-hidden mb-8 h-44 sm:h-52">
                    <img src={cat.image} alt={cat.name} className="absolute inset-0 w-full h-full object-cover" />
                    <div className="absolute inset-0 bg-gradient-to-r from-slate-950/90 via-slate-950/60 to-transparent" />
                    <div className="relative z-10 h-full flex flex-col justify-center px-6 sm:px-10 max-w-xl">
                      <span className="text-teal-300 font-black text-sm">
                        {String(idx + 1).padStart(2, "0")}
                      </span>
                      <h2 className="text-2xl sm:text-3xl font-black text-white mt-1">{cat.name}</h2>
                      <p className="text-slate-200 text-xs sm:text-sm mt-1 line-clamp-2">{cat.description}</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 sm:gap-6">
                    {catProducts.map((p) => (
                      <ProductCard key={p.id} product={p} />
                    ))}
                  </div>
                </div>
              </section>
            );
          })
        )}
      </div>

      {/* Bulk Quote CTA */}
      <section className="py-14 bg-gradient-to-r from-teal-600 via-teal-500 to-emerald-500 text-white">
        <div className="max-w-4xl mx-auto px-4 text-center space-y-4">
          <Sparkles className="w-8 h-8 mx-auto text-white/90" />
          <h2 className="text-2xl sm:text-3xl font-black">Ordering for a School or Business?</h2>
          <p className="text-sm sm:text-base text-teal-50 max-w-2xl mx-auto">
            Request a formal quotation on any items in this catalogue and unlock volume discounts, official VAT invoices and dedicated account support.
          </p>
          <div className="flex flex-wrap justify-center gap-3 pt-2">
            <button
              onClick={() => setIsQuoteModalOpen(true)}
              className="px-6 py-3.5 bg-slate-950 hover:bg-slate-900 text-white font-black text-sm rounded-2xl shadow-xl flex items-center gap-2 transition-all"
            >
              <FileCheck2 className="w-4 h-4 text-teal-300" /> Request Bulk Quote
            </button>
            <Link
              href="/price-list"
              className="px-6 py-3.5 bg-white/15 hover:bg-white/25 text-white font-bold text-sm rounded-2xl border border-white/30 backdrop-blur-sm flex items-center gap-2 transition-all"
            >
              <ListChecks className="w-4 h-4" /> Download Price List
            </Link>
          </div>
        </div>
      </section>

      <Footer />

      <ProductModal />
      <CartDrawer />
      <CheckoutModal />
      <OrderTrackerModal />
      <BulkQuoteModal />
      <WhatsAppButton />
    </div>
  );
}

export default function CataloguePage() {
  return (
    <CartProvider>
      <CatalogueContent />
    </CartProvider>
  );
}
