"use client";

import React, { useState, useEffect } from "react";
import { CartProvider, useCart } from "@/context/CartContext";
import { Header } from "@/components/Header";
import { Hero } from "@/components/Hero";
import { CategoryGrid } from "@/components/CategoryGrid";
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 { DeliveryCalculator } from "@/components/DeliveryCalculator";
import { BrandLogos } from "@/components/BrandLogos";
import { CustomerReviews } from "@/components/CustomerReviews";
import { Footer } from "@/components/Footer";
import { MobileBottomNav } from "@/components/MobileBottomNav";
import { WhatsAppButton } from "@/components/WhatsAppButton";
import { Product, Category } from "@/types";
import {
  Sparkles,
  Flame,
  GraduationCap,
  Percent,
  SlidersHorizontal,
  FileCheck2,
  CheckCircle2,
  PackageCheck,
  Search,
} from "lucide-react";

function MainShop() {
  const { setIsQuoteModalOpen, setIsTrackerOpen } = useCart();

  const [categories, setCategories] = useState<Category[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);

  // Filters & Sorting state
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [activeTabFilter, setActiveTabFilter] = useState<"all" | "best_sellers" | "special_offers" | "school_essentials">("all");
  const [sortBy, setSortBy] = useState("newest");
  const [query, setQuery] = useState("");

  // Fetch initial data
  useEffect(() => {
    fetchCategories();
  }, []);

  useEffect(() => {
    fetchProducts();
  }, [selectedCategory, activeTabFilter, sortBy, query]);

  const fetchCategories = async () => {
    try {
      const res = await fetch("/api/categories");
      const data = await res.json();
      if (data.categories) setCategories(data.categories);
    } catch (err) {
      console.error(err);
    }
  };

  const fetchProducts = async () => {
    setLoading(true);
    try {
      let url = `/api/products?sort=${sortBy}`;
      if (selectedCategory !== "all" && selectedCategory !== "special_offers") {
        url += `&category=${selectedCategory}`;
      }
      if (activeTabFilter !== "all") {
        url += `&filter=${activeTabFilter}`;
      } else if (selectedCategory === "special_offers") {
        url += `&filter=special_offers`;
      }
      if (query) {
        url += `&query=${encodeURIComponent(query)}`;
      }

      const res = await fetch(url);
      const data = await res.json();
      if (data.products) setProducts(data.products);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const handleCategorySelect = (catId: string) => {
    setSelectedCategory(catId);
    setActiveTabFilter("all");
    const el = document.getElementById("catalog-section");
    if (el) {
      el.scrollIntoView({ behavior: "smooth" });
    }
  };

  return (
    <div className="min-h-screen flex flex-col bg-slate-100 font-sans text-slate-900 pb-16 lg:pb-0">
      {/* Header Navigation */}
      <Header
        categories={categories}
        onSelectCategory={handleCategorySelect}
        selectedCategory={selectedCategory}
      />

      {/* Hero Banner */}
      <Hero
        onShopNowClick={() => {
          const el = document.getElementById("catalog-section");
          if (el) el.scrollIntoView({ behavior: "smooth" });
        }}
        onSelectCategory={handleCategorySelect}
        onRequestQuoteClick={() => setIsQuoteModalOpen(true)}
      />

      {/* Category Grid Section */}
      <CategoryGrid
        categories={categories}
        selectedCategory={selectedCategory}
        onSelectCategory={handleCategorySelect}
      />

      {/* Main Catalog Products Section */}
      <section id="catalog-section" className="py-12 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto w-full flex-1">
        {/* Catalog Control Header */}
        <div className="flex flex-col md:flex-row md:items-center justify-between pb-6 border-b border-slate-200 gap-4">
          <div>
            <div className="flex items-center gap-2">
              <span className="text-xs font-extrabold uppercase tracking-wider text-amber-700 bg-amber-100 px-3 py-1 rounded-full">
                South Africa Store
              </span>
              <span className="text-xs text-slate-500 font-medium">
                {products.length} {products.length === 1 ? "Product" : "Products"} Available
              </span>
            </div>
            <h2 className="text-2xl sm:text-3xl font-black text-slate-900 mt-1">
              {selectedCategory === "all"
                ? "All Stationery & Office Supplies"
                : categories.find((c) => c.id === selectedCategory)?.name || "Category Products"}
            </h2>
          </div>

          {/* Filter Tabs */}
          <div className="flex items-center gap-2 overflow-x-auto no-scrollbar py-1">
            <button
              onClick={() => setActiveTabFilter("all")}
              className={`px-3.5 py-2 text-xs font-bold rounded-xl transition-all whitespace-nowrap cursor-pointer ${
                activeTabFilter === "all"
                  ? "bg-blue-950 text-white shadow-md"
                  : "bg-white text-slate-700 border border-slate-200 hover:bg-slate-50"
              }`}
            >
              All Items
            </button>

            <button
              onClick={() => setActiveTabFilter("best_sellers")}
              className={`px-3.5 py-2 text-xs font-bold rounded-xl transition-all whitespace-nowrap flex items-center gap-1 cursor-pointer ${
                activeTabFilter === "best_sellers"
                  ? "bg-amber-500 text-slate-950 shadow-md"
                  : "bg-white text-slate-700 border border-slate-200 hover:bg-slate-50"
              }`}
            >
              <Flame className="w-3.5 h-3.5 text-amber-600 fill-amber-500" /> Best Sellers
            </button>

            <button
              onClick={() => setActiveTabFilter("school_essentials")}
              className={`px-3.5 py-2 text-xs font-bold rounded-xl transition-all whitespace-nowrap flex items-center gap-1 cursor-pointer ${
                activeTabFilter === "school_essentials"
                  ? "bg-blue-900 text-white shadow-md"
                  : "bg-white text-slate-700 border border-slate-200 hover:bg-slate-50"
              }`}
            >
              <GraduationCap className="w-3.5 h-3.5 text-amber-400" /> School Essentials
            </button>

            <button
              onClick={() => setActiveTabFilter("special_offers")}
              className={`px-3.5 py-2 text-xs font-bold rounded-xl transition-all whitespace-nowrap flex items-center gap-1 cursor-pointer ${
                activeTabFilter === "special_offers"
                  ? "bg-rose-600 text-white shadow-md"
                  : "bg-white text-slate-700 border border-slate-200 hover:bg-slate-50"
              }`}
            >
              <Percent className="w-3.5 h-3.5" /> Special Offers
            </button>

            {/* Sort Dropdown */}
            <div className="ml-auto flex items-center gap-2 bg-white border border-slate-200 rounded-xl px-3 py-1.5 shrink-0">
              <SlidersHorizontal className="w-3.5 h-3.5 text-slate-500" />
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="text-xs font-bold bg-transparent text-slate-800 focus:outline-none"
              >
                <option value="newest">Sort by: Newest</option>
                <option value="price_asc">Price: Low to High</option>
                <option value="price_desc">Price: High to Low</option>
                <option value="rating">Highest Rated</option>
              </select>
            </div>
          </div>
        </div>

        {/* Product Grid Area */}
        <div className="mt-8">
          {loading ? (
            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 sm:gap-6 animate-pulse">
              {[...Array(8)].map((_, i) => (
                <div key={i} className="bg-slate-200 rounded-2xl h-80"></div>
              ))}
            </div>
          ) : products.length === 0 ? (
            <div className="p-12 text-center bg-white rounded-3xl border border-slate-200 shadow-sm max-w-md mx-auto my-6">
              <Search className="w-10 h-10 text-slate-400 mx-auto mb-3" />
              <h3 className="font-extrabold text-slate-900 text-lg">No products found</h3>
              <p className="text-xs text-slate-500 mt-1">
                Try resetting your category filters or search for another item like &ldquo;BIC&rdquo; or &ldquo;Paper&rdquo;.
              </p>
              <button
                onClick={() => {
                  setSelectedCategory("all");
                  setActiveTabFilter("all");
                }}
                className="mt-4 px-4 py-2 bg-blue-950 text-white font-bold text-xs rounded-xl hover:bg-slate-900"
              >
                Show All Products
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 sm:gap-6">
              {products.map((product) => (
                <ProductCard key={product.id} product={product} />
              ))}
            </div>
          )}
        </div>
      </section>

      {/* Special Bulk Quote Callout Banner */}
      <section className="py-12 bg-gradient-to-r from-amber-500 via-amber-400 to-yellow-400 text-slate-950">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col lg:flex-row items-center justify-between gap-6">
          <div className="space-y-1 text-center lg:text-left">
            <span className="text-xs font-black uppercase tracking-wider bg-slate-950 text-white px-3 py-1 rounded-full">
              School Lists & Corporate Accounts
            </span>
            <h3 className="text-2xl sm:text-3xl font-black text-slate-950 mt-1">
              Need Bulk Quantities or Custom School Stationery Packs?
            </h3>
            <p className="text-xs sm:text-sm font-semibold text-slate-900 max-w-2xl">
              We supply schools, universities, law firms, accounting practices & government departments with official Tax Invoice quotes and bulk discounts.
            </p>
          </div>

          <button
            onClick={() => setIsQuoteModalOpen(true)}
            className="px-6 py-3.5 bg-slate-950 hover:bg-slate-900 text-white font-black text-xs sm:text-sm rounded-2xl shadow-xl transition-all flex items-center gap-2 cursor-pointer shrink-0"
          >
            <FileCheck2 className="w-4 h-4 text-amber-400" />
            <span>REQUEST BULK QUOTE NOW</span>
          </button>
        </div>
      </section>

      {/* Delivery Calculator */}
      <div id="delivery-calculator">
        <DeliveryCalculator />
      </div>

      {/* Brand Logos */}
      <BrandLogos />

      {/* Customer Reviews */}
      <CustomerReviews />

      {/* Footer */}
      <Footer />

      {/* Interactive Modals & Drawers */}
      <ProductModal />
      <CartDrawer />
      <CheckoutModal />
      <OrderTrackerModal />
      <BulkQuoteModal />

      {/* Floating Buttons */}
      <WhatsAppButton />
      <MobileBottomNav
        onSelectCategory={handleCategorySelect}
        selectedCategory={selectedCategory}
      />
    </div>
  );
}

export default function Home() {
  return (
    <CartProvider>
      <MainShop />
    </CartProvider>
  );
}
