import { createFileRoute, Link } from "@tanstack/react-router";
import { useState, useEffect } from "react";
import { Header } from "@/components/site/Header";
import { Footer } from "@/components/site/Footer";
import { SignInModal, CartDrawer, CheckoutFlow } from "@/components/site/Modals";
import { Button } from "@/components/ui/button";
import { Phone, Store, Package, ChevronLeft, ChevronRight, BadgeCheck, Sparkles } from "lucide-react";
import { useStore, fmt, Product } from "@/lib/store";
import { CATEGORIES, slugify } from "@/lib/categories";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "SulejaMarket — Online Shopping for Electronics, Fashion & More" },
      { name: "description", content: "Shop the best deals on phones, electronics, fashion, groceries and more. Flash sales daily." },
      { property: "og:title", content: "SulejaMarket — Online Shopping" },
      { property: "og:description", content: "Flash sales, top sellers and limited stock deals up to 70% off." },
    ],
  }),
  component: Home,
});

const gridCats = [
  "Phones & Tablets", "Appliances", "Kids, Baby And More", "Fashion Deals", "Beauty Must Have", "Sneakers Deals",
  "New Arrival", "Home & Office deals", "Beverages deals", "Mobile Accessories deals", "Computing deals", "Buy now, Pay Small Small",
];

function Home() {
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [activeBanner, setActiveBanner] = useState(0);
  const { addToCart, getAllProducts, topBanners, heroBanners, vendorProducts } = useStore();

  useEffect(() => {
    if (!heroBanners || heroBanners.length === 0) return;
    const timer = setInterval(() => {
      setActiveBanner((prev) => (prev + 1) % heroBanners.length);
    }, 5000);
    return () => clearInterval(timer);
  }, [heroBanners]);

  const all = getAllProducts();
  const featuredProds = all.filter(p => p.is_featured);

  let flash = all.filter(p => p.is_flash);
  if (flash.length === 0) flash = all.slice(0, 6);

  let top = all.filter(p => p.is_top);
  if (top.length === 0) top = all.slice(6, 12);

  return (
    <div className="min-h-screen" style={{ backgroundColor: "#f0f2f5" }}>
      <SignInModal open={signInOpen} onOpenChange={setSignInOpen} />
      <CartDrawer open={cartOpen} onOpenChange={setCartOpen} onCheckout={() => { setCartOpen(false); setCheckoutOpen(true); }} />
      <CheckoutFlow open={checkoutOpen} onOpenChange={setCheckoutOpen} />

      <Header onOpenCart={() => setCartOpen(true)} onOpenSignIn={() => setSignInOpen(true)} />

      <main className="max-w-[1200px] mx-auto px-4 py-4 space-y-4">
        <section className="flex flex-col lg:grid lg:grid-cols-12 gap-3 lg:h-[384px]">
          <aside className="hidden lg:block col-span-3 bg-white rounded-md py-2 text-sm overflow-y-auto no-scrollbar">
            {CATEGORIES.map((c) => (
              <Link
                key={c}
                to="/category/$slug"
                params={{ slug: slugify(c) }}
                className="block px-4 py-1.5 hover:bg-orange-50 hover:text-orange-600 cursor-pointer"
              >
                {c}
              </Link>
            ))}
          </aside>
          <div className="lg:col-span-6 rounded-md overflow-hidden bg-neutral-200 relative group h-[200px] sm:h-[280px] lg:h-full">
            {heroBanners && heroBanners.length > 0 ? (
              <a href={heroBanners[activeBanner]?.link || "#"} className="block w-full h-full">
                <img 
                  src={heroBanners[activeBanner]?.image} 
                  alt="Featured deals banner" 
                  className="w-full h-full object-cover transition-opacity duration-500" 
                />
              </a>
            ) : (
              <div className="w-full h-full min-h-[280px] flex items-center justify-center text-sm text-neutral-500">No banners</div>
            )}
            
            {heroBanners && heroBanners.length > 1 && (
              <div className="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-1.5 z-10">
                {heroBanners.map((_, i) => (
                  <button 
                    key={i} 
                    onClick={(e) => { e.preventDefault(); setActiveBanner(i); }}
                    className={`h-1.5 rounded-full transition-all ${i === activeBanner ? "w-4 bg-white" : "w-1.5 bg-white/50 hover:bg-white/80"}`} 
                    aria-label={`Go to slide ${i + 1}`}
                  />
                ))}
              </div>
            )}
          </div>
          <div className="lg:col-span-3 flex lg:flex-col gap-3 overflow-x-auto no-scrollbar pb-1 lg:pb-0">
            <Promo icon={<Phone className="w-5 h-5" />} title="CALL TO ORDER" sub="081 0265 8259" />
            <Link to="/vendor" className="block shrink-0"><Promo icon={<Store className="w-5 h-5" />} title="Sell on SulejaMarket" /></Link>
            <Promo icon={<Package className="w-5 h-5" />} title="Send your Package" />
          </div>
        </section>

        <section className="bg-white rounded-md p-3">
          <div className="flex items-center gap-2">
            <button className="w-7 h-7 rounded-full bg-neutral-100 flex items-center justify-center shrink-0"><ChevronLeft className="w-4 h-4" /></button>
            <div className="flex-1 overflow-x-auto no-scrollbar">
              <div className="flex gap-4 min-w-max px-2 py-1">
                {topBanners.map((b) => (
                  <div key={b.id} className="flex flex-col items-center gap-1 w-[100px]">
                    <div className="w-[100px] h-[100px] rounded-full overflow-hidden bg-neutral-100 shrink-0">
                      <img src={b.image} alt={b.title} className="w-full h-full object-cover" />
                    </div>
                    <span className="text-[11px] text-center text-neutral-700 leading-tight">{b.title}</span>
                  </div>
                ))}
              </div>
            </div>
            <button className="w-7 h-7 rounded-full bg-neutral-100 flex items-center justify-center shrink-0"><ChevronRight className="w-4 h-4" /></button>
          </div>
        </section>

        {/* Featured Vendor Products Section */}
        {featuredProds.length > 0 && (
          <section className="bg-white rounded-md overflow-hidden border-2 border-amber-400 shadow-sm">
            <div className="bg-gradient-to-r from-amber-500 via-orange-500 to-amber-600 text-white px-4 py-2.5 flex items-center justify-between font-bold">
              <span className="flex items-center gap-2 text-base">
                <Sparkles className="w-5 h-5 text-amber-200 fill-amber-300 animate-pulse" /> Featured Vendor Products
              </span>
              <span className="text-xs text-amber-100 font-normal">Promoted by Sellers with Loyalty Coins</span>
            </div>
            <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6">
              {featuredProds.map((p) => (
                <ProductCard key={p.id} p={p} onAdd={() => addToCart(p)} />
              ))}
            </div>
          </section>
        )}

        <section className="bg-white rounded-md overflow-hidden">
          <div className="bg-[#c8103e] text-white px-4 py-2.5 flex items-center justify-between">
            <div className="flex items-center gap-4 font-semibold">
              <span>⚡ Flash Sales</span>
              <span className="text-sm font-normal opacity-90">Time Left: <b>12h : 02m : 26s</b></span>
            </div>
            <a className="text-sm cursor-pointer hover:underline">See all</a>
          </div>
          <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6">
            {flash.map((p) => (
              <ProductCard key={p.id} p={p} onAdd={() => addToCart(p)} sold={20} />
            ))}
          </div>
        </section>

        <section className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6 gap-3">
          {gridCats.map((c, i) => (
            <Link key={i} to="/category/$slug" params={{ slug: slugify(c) }} className="bg-white rounded-md p-3 flex flex-col items-center gap-2 hover:shadow-md transition">
              <img src={`https://picsum.photos/seed/gc${i}/200/200`} alt={c} className="w-full aspect-square object-cover rounded" />
              <span className="text-xs text-neutral-700 text-center hover:text-orange-500">{c}</span>
            </Link>
          ))}
        </section>

        <section className="bg-white rounded-md overflow-hidden">
          <div className="bg-orange-400 text-white px-4 py-2.5 flex items-center justify-between font-semibold">
            <span>Top Sellers</span><a className="text-sm cursor-pointer hover:underline">See all</a>
          </div>
          <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6">
            {top.map((p) => (<ProductCard key={p.id} p={p} onAdd={() => addToCart(p)} />))}
          </div>
        </section>

        {vendorProducts.length > 0 && (
          <section className="bg-white rounded-md overflow-hidden">
            <div className="bg-emerald-500 text-white px-4 py-2.5 flex items-center justify-between font-semibold">
              <span>🌟 Fresh from our Vendors</span>
              <Link to="/vendor" className="text-sm hover:underline">Manage listings</Link>
            </div>
            <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6">
              {vendorProducts.map((p) => (<ProductCard key={p.id} p={p} onAdd={() => addToCart(p)} />))}
            </div>
          </section>
        )}

      </main>
      <Footer />
    </div>
  );
}

function Promo({ icon, title, sub }: { icon: React.ReactNode; title: string; sub?: string }) {
  return (
    <div className="bg-white rounded-md px-3 py-2.5 flex items-center gap-3 text-sm shrink-0 min-w-[220px] lg:min-w-0 lg:w-full">
      <div className="text-orange-500">{icon}</div>
      <div>
        <div className="font-medium text-neutral-800">{title}</div>
        {sub && <div className="text-xs text-neutral-500">{sub}</div>}
      </div>
    </div>
  );
}

function ProductCard({ p, onAdd, sold }: { p: Product; onAdd: () => void; sold?: number }) {
  const { vendors } = useStore();
  const vendor = vendors.find(v => v.contactEmail === p.vendorEmail);
  const isVerified = vendor?.is_verified;

  return (
    <div id={p.id} className="border-r border-b last:border-r-0 p-3 relative bg-white hover:shadow-md transition group">
      <Link to="/product/$id" params={{ id: p.id }} className="block">
        <div className="relative">
          <img src={(p.images?.[0] || `https://picsum.photos/seed/${p.seed}/240/240`)} alt={p.name} className="w-full aspect-square object-cover rounded" />
          {p.is_featured && (
            <span className="absolute top-1 left-1 bg-gradient-to-r from-amber-500 to-orange-500 text-white text-[10px] font-extrabold px-2 py-0.5 rounded-full shadow-md flex items-center gap-1 z-10">
              <Sparkles className="w-3 h-3 text-amber-200 fill-amber-100" /> Featured
            </span>
          )}
          {p.disc && <span className="absolute top-1 right-1 bg-orange-100 text-orange-700 text-[11px] font-bold px-1.5 py-0.5 rounded">{p.disc}</span>}
        </div>
        <div className="mt-2 space-y-0.5">
          <div className="text-xs text-neutral-700 line-clamp-1 flex items-center gap-1">
            {p.name}
            {isVerified && <span className="inline-flex"><BadgeCheck className="w-3.5 h-3.5 text-sky-500" /></span>}
          </div>
          <div className="text-sm font-bold text-neutral-900">₦ {fmt(p.price)}</div>
          {p.old && <div className="text-[11px] text-neutral-400 line-through">₦ {fmt(p.old)}</div>}
          {sold !== undefined && (
            <div className="mt-1">
              <div className="h-1.5 rounded-full bg-orange-100 overflow-hidden">
                <div className="h-full bg-orange-500" style={{ width: `${Math.min(100, sold * 3)}%` }} />
              </div>
              <div className="text-[10px] text-neutral-500 mt-0.5">{sold} items sold</div>
            </div>
          )}
        </div>
      </Link>
      <Button onClick={onAdd} size="sm" className="w-full mt-2 h-8 bg-orange-500 hover:bg-orange-600 text-white text-xs">Add to cart</Button>
    </div>
  );
}
