"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { ArrowLeft, BadgeCheck, Bike, CakeSlice, Clock3, Cookie, CupSoda, Headphones, Leaf, Package, RotateCcw, ShieldCheck, ShoppingBasket, Sparkles, SprayCan, Star, Truck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ProductCard } from "@/components/product-card";
import { StoreShell } from "@/components/store-shell";
import { DEFAULT_SITE_SETTINGS, resolveSiteSettings, type HomeSection, type SiteSettings } from "@/data/site-defaults";
import { getDiscountPercent, type Product } from "@/lib/commerce";

const CATEGORY_COLORS = ["#e8fff4", "#fff0f7", "#fff8df", "#eff6ff", "#f3e8ff", "#ecfeff", "#fff1f2", "#f0fdf4", "#fff7ed"];
const CATEGORY_ICONS = [CupSoda, Package, ShoppingBasket, Sparkles, SprayCan, Leaf, Package, CakeSlice, Cookie];

export function Storefront({ initialProducts }: { initialProducts: Product[] }) {
  const [products, setProducts] = useState(initialProducts);
  const [settings, setSettings] = useState<SiteSettings>(DEFAULT_SITE_SETTINGS);

  useEffect(() => {
    Promise.all([
      fetch("/api/products?limit=240").then((response) => response.ok ? response.json() : null),
      fetch("/api/settings").then((response) => response.ok ? response.json() : null),
    ]).then(([catalog, site]) => {
      if (catalog?.products?.length) setProducts(catalog.products);
      if (site?.settings) setSettings(resolveSiteSettings(site.settings));
    }).catch(() => undefined);
  }, []);

  const visibleProducts = useMemo(() => products.filter((product) => product.active), [products]);
  const categories = useMemo(() => [...new Set(visibleProducts.map((product) => product.category))], [visibleProducts]);

  return (
    <StoreShell categories={categories}>
      <div className="container-shell space-y-9 py-4 md:py-6">
        {settings.hero.enabled && <Hero settings={settings} />}
        {settings.homeSections.filter((section) => section.enabled).map((section) => (
          <SectionRenderer key={section.id} section={section} products={visibleProducts} categories={categories} settings={settings} />
        ))}
        <AppBanner settings={settings} />
      </div>
    </StoreShell>
  );
}

function Hero({ settings }: { settings: SiteSettings }) {
  return (
    <section className="soft-rise relative min-h-[310px] overflow-hidden rounded-[var(--shop-radius)] border border-emerald-100 bg-[#f7fff7] glass-shadow md:min-h-[400px]">
      <img src={settings.hero.imageUrl} alt="خرید تازه و روزانه از barzinmarket" className="absolute inset-0 h-full w-full object-cover object-left" />
      <div className="absolute inset-0 bg-gradient-to-l from-white via-white/92 via-45% to-transparent dark:from-slate-950 dark:via-slate-950/85" />
      <div className="relative z-10 flex min-h-[310px] max-w-[690px] flex-col justify-center px-7 py-10 md:min-h-[400px] md:px-14">
        <div className="mb-4 flex w-fit items-center gap-2 rounded-full border border-emerald-200 bg-white/85 px-4 py-2 text-sm font-black text-emerald-700 shadow-sm backdrop-blur"><Sparkles className="h-4 w-4 text-[var(--shop-accent)]" />{settings.hero.eyebrow}</div>
        <h1 className="max-w-xl text-3xl font-black leading-[1.55] text-[var(--shop-navy)] sm:text-5xl md:text-[3.4rem] dark:text-white">{settings.hero.title}</h1>
        <p className="mt-3 max-w-xl text-base leading-8 text-slate-600 md:text-lg dark:text-slate-300">{settings.hero.subtitle}</p>
        <div className="mt-6 flex flex-wrap gap-3">
          <Button size="lg" className="h-12 rounded-xl bg-[var(--shop-primary)] px-7 text-base font-black text-white hover:brightness-95" asChild><Link href={settings.hero.buttonHref}>{settings.hero.buttonLabel}<ArrowLeft className="mr-2 h-5 w-5" /></Link></Button>
          <Button size="lg" variant="outline" className="h-12 rounded-xl border-emerald-200 bg-white/80 px-6 text-emerald-800 hover:bg-emerald-50" asChild><Link href="/search">{settings.labels.allProducts}</Link></Button>
        </div>
        <div className="mt-6 flex flex-wrap gap-x-5 gap-y-2 text-xs font-bold text-slate-600">
          <span className="flex items-center gap-1.5"><Clock3 className="h-4 w-4 text-[var(--shop-primary)]" />تحویل سریع و زمان‌بندی‌شده</span>
          <span className="flex items-center gap-1.5"><BadgeCheck className="h-4 w-4 text-[var(--shop-primary)]" />تضمین سلامت کالا</span>
        </div>
      </div>
    </section>
  );
}

function SectionRenderer({ section, products, categories, settings }: { section: HomeSection; products: Product[]; categories: string[]; settings: SiteSettings }) {
  if (section.type === "categories") return <CategorySection section={section} categories={categories} settings={settings} />;
  if (section.type === "services") return <ServiceSection section={section} />;
  if (section.type === "offers") {
    const rows = products.filter((product) => getDiscountPercent(product) > 0).sort((a, b) => getDiscountPercent(b) - getDiscountPercent(a)).slice(0, section.limit);
    return <ProductRail section={section} products={rows} offers />;
  }
  if (section.type === "products") {
    const rows = section.source === "featured" ? products.filter((product) => product.featured) : [...products].reverse();
    return <ProductRail section={section} products={rows.slice(0, section.limit)} />;
  }
  return null;
}

function CategorySection({ section, categories, settings }: { section: HomeSection; categories: string[]; settings: SiteSettings }) {
  return (
    <section id={section.id}>
      <SectionTitle title={section.title} subtitle={section.subtitle} href="/search" />
      <div className="grid grid-cols-3 gap-3 sm:grid-cols-5 lg:grid-cols-9">
        {categories.slice(0, section.limit).map((category, index) => {
          const Icon = CATEGORY_ICONS[index] ?? Package;
          return (
            <Link key={category} href={`/search?category=${encodeURIComponent(category)}`} className="group flex flex-col items-center gap-3 rounded-[var(--shop-card-radius)] border border-slate-200/80 bg-white p-3 text-center transition hover:-translate-y-1 hover:border-emerald-200 hover:shadow-lg dark:border-slate-700 dark:bg-slate-900">
              <span className={`grid aspect-square w-full max-w-[88px] place-items-center transition group-hover:scale-105 ${settings.layout.categoryShape === "circle" ? "rounded-full" : "rounded-[22px]"}`} style={{ background: CATEGORY_COLORS[index % CATEGORY_COLORS.length] }}><Icon className="h-9 w-9 text-[var(--shop-primary)]" /></span>
              <span className="line-clamp-2 text-sm font-black text-slate-700 dark:text-slate-100">{category}</span>
            </Link>
          );
        })}
      </div>
    </section>
  );
}

function ProductRail({ section, products, offers = false }: { section: HomeSection; products: Product[]; offers?: boolean }) {
  if (!products.length) return null;
  return (
    <section id={section.id} className={offers ? "relative overflow-hidden rounded-[var(--shop-radius)] bg-[var(--shop-primary)] p-4 md:p-6" : ""}>
      {offers && <div className="pointer-events-none absolute -left-20 -top-24 h-80 w-80 rounded-full bg-white/10 blur-2xl" />}
      <div className="relative"><SectionTitle title={section.title} subtitle={section.subtitle} href="/search" inverse={offers} />
        <div className={`scroll-snap-x grid auto-cols-[minmax(190px,220px)] grid-flow-col gap-3 overflow-x-auto pb-2 ${offers ? "md:auto-cols-[230px]" : "md:auto-cols-[240px]"}`}>
          {products.map((product) => <ProductCard key={product.id} product={product} emphasis={offers} />)}
        </div>
      </div>
    </section>
  );
}

function ServiceSection({ section }: { section: HomeSection }) {
  const services = [
    { icon: Bike, title: "تحویل سریع", text: "انتخاب ارسال فوری یا بازه زمانی دلخواه" },
    { icon: BadgeCheck, title: "سلامت کالا", text: "کنترل کیفیت و تاریخ مصرف سفارش" },
    { icon: RotateCcw, title: "بازگشت آسان", text: "ثبت درخواست مرجوعی از حساب مشتری" },
    { icon: ShieldCheck, title: "پرداخت امن", text: "پرداخت آنلاین یا هنگام تحویل" },
    { icon: Headphones, title: "پشتیبانی", text: "پیگیری سفارش و پاسخ‌گویی سریع" },
    { icon: Star, title: "باشگاه مشتریان", text: "امتیاز و پاداش برای خریدهای بعدی" },
  ];
  return (
    <section id={section.id}>
      <SectionTitle title={section.title} subtitle={section.subtitle} />
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-6">
        {services.slice(0, section.limit).map(({ icon: Icon, title, text }) => (
          <div key={title} className="rounded-[var(--shop-card-radius)] border border-slate-200/80 bg-white p-5 dark:border-slate-700 dark:bg-slate-900">
            <span className="mb-4 grid h-11 w-11 place-items-center rounded-2xl bg-emerald-50 text-[var(--shop-primary)] dark:bg-emerald-950"><Icon className="h-6 w-6" /></span>
            <h3 className="font-black">{title}</h3><p className="mt-2 text-xs leading-6 text-slate-500">{text}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function AppBanner({ settings }: { settings: SiteSettings }) {
  return (
    <section className="relative overflow-hidden rounded-[var(--shop-radius)] bg-[var(--shop-navy)] px-7 py-9 text-white md:px-12">
      <div className="absolute -left-16 -top-20 h-72 w-72 rounded-full bg-emerald-300/15 blur-3xl" />
      <div className="relative flex flex-col items-start justify-between gap-6 md:flex-row md:items-center">
        <div><span className="rounded-full bg-white/10 px-3 py-1 text-xs font-bold text-emerald-200">همیشه همراه شما</span><h2 className="mt-4 text-2xl font-black md:text-3xl">{settings.labels.mobileBannerTitle}</h2><p className="mt-2 text-sm leading-7 text-slate-300">{settings.labels.mobileBannerText}</p></div>
        <div className="flex flex-wrap gap-2"><Button variant="secondary" className="rounded-xl">نسخه اندروید</Button><Button variant="outline" className="rounded-xl border-white/30 bg-transparent text-white hover:bg-white hover:text-slate-950">نسخه وب‌اپ</Button></div>
      </div>
    </section>
  );
}

function SectionTitle({ title, subtitle, href, inverse = false }: { title: string; subtitle: string; href?: string; inverse?: boolean }) {
  return (
    <div className={`mb-5 flex items-end justify-between gap-4 ${inverse ? "text-white" : ""}`}>
      <div><h2 className="text-xl font-black md:text-2xl">{title}</h2><p className={`mt-1 text-sm ${inverse ? "text-white/75" : "text-slate-500"}`}>{subtitle}</p></div>
      {href && <Link href={href} className={`flex shrink-0 items-center gap-1 text-sm font-black ${inverse ? "text-white" : "text-[var(--shop-primary)]"}`}>مشاهده همه<ArrowLeft className="h-4 w-4" /></Link>}
    </div>
  );
}
