 "use client";

import { useState, useEffect } from "react";
import Header from "@/components/layout/Header";
import Hero from "@/components/home/Hero";
import BannerSlider from "@/components/home/BannerSlider";
import CategorySection from "@/components/home/CategorySection";
import NewArrivals from "@/components/home/NewArrivals";
import dynamic from "next/dynamic";
import ProductCard from "@/components/product/ProductCard";
import Footer from "@/components/layout/Footer";
import Link from "next/link";
import { motion } from "framer-motion";
import { Zap, Tag, ArrowRight } from "lucide-react";
import { api } from "@/lib/api";
import { Product } from "@/types";
import Image from "next/image";
import { useSettings } from "@/context/SettingsContext";
import ProductCardSkeleton from "@/components/product/ProductCardSkeleton";

const CouponSection = dynamic(() => import("@/components/home/CouponSection"), {
  ssr: false,
});

const ReviewSection = dynamic(() => import("@/components/home/ReviewSection"), {
  ssr: false,
});

export default function HomeClient() {
  const [featuredProducts, setFeaturedProducts] = useState<Product[]>([]);
  const [popularProducts, setPopularProducts] = useState<Product[]>([]);
  const [flashSale, setFlashSale] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const { settings, currency } = useSettings();

  const renderIcon = (iconStr: string, className: string = "") => {
    if (!iconStr) return null;
    if (
      iconStr.includes("fa-") ||
      iconStr.startsWith("fas ") ||
      iconStr.startsWith("fab ") ||
      iconStr.startsWith("far ")
    ) {
      return <i className={`${iconStr} ${className}`}></i>;
    }
    return <span className={className}>{iconStr}</span>;
  };

  useEffect(() => {
    const fetchHomeData = async () => {
      try {
        setLoading(true);
        const [productsRes, popularRes, flashSaleRes] = await Promise.all([
          api
            .getProducts({ is_featured: true })
            .catch(() => ({ data: [] })),
          api
            .getPopularProducts()
            .catch(() => ({ data: [] })),
          api.getFlashSale().catch(() => ({ data: null })),
        ]);

        const products = Array.isArray(productsRes.data)
          ? productsRes.data
          : (productsRes as any).data?.data || [];
        const popular = Array.isArray(popularRes.data)
          ? popularRes.data
          : [];
        const saleData = (flashSaleRes as any)?.data || null;

        setFeaturedProducts(
          products.length > 0
            ? products.slice(0, 8)
            : []
        );
        setPopularProducts(
          popular.length > 0
            ? popular.slice(0, 4)
            : []
        );
        setFlashSale(saleData);
      } catch (error) {
        setFeaturedProducts([]);
        setPopularProducts([]);
      } finally {
        setLoading(false);
      }
    };

    fetchHomeData();
  }, []);

  const [timeLeft, setTimeLeft] = useState({
    days: "00",
    hours: "00",
    mins: "00",
    secs: "00",
  });

  useEffect(() => {
    let interval: any;

    const setupTimer = () => {
      let targetEnd: number | null = null;

      if (flashSale?.is_active && flashSale?.end_at) {
        const parsed = new Date(flashSale.end_at);
        if (!isNaN(parsed.getTime())) {
          targetEnd = parsed.getTime();
        }
      }

      if (!targetEnd) {
        const endOfDay = new Date();
        endOfDay.setHours(23, 59, 59, 999);
        targetEnd = endOfDay.getTime();
      }

      interval = setInterval(() => {
        const now = new Date().getTime();
        const diff = (targetEnd as number) - now;

        if (diff <= 0) {
          clearInterval(interval);
          setTimeLeft({
            days: "00",
            hours: "00",
            mins: "00",
            secs: "00",
          });
          return;
        }
        const dayMs = 1000 * 60 * 60 * 24;
        const hourMs = 1000 * 60 * 60;
        const minMs = 1000 * 60;

        const d = Math.floor(diff / dayMs);
        const h = Math.floor((diff % dayMs) / hourMs);
        const m = Math.floor((diff % hourMs) / minMs);
        const s = Math.floor((diff % minMs) / 1000);

        setTimeLeft({
          days: d.toString().padStart(2, "0"),
          hours: h.toString().padStart(2, "0"),
          mins: m.toString().padStart(2, "0"),
          secs: s.toString().padStart(2, "0"),
        });
      }, 1000);
    };

    setupTimer();

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [flashSale]);

  useEffect(() => {
    const track = async () => {
      try {
        await api.trackVisit("/");
      } catch (error) {}
    };
    track();
  }, []);

  const flashSaleProducts: Product[] =
    flashSale?.is_active &&
    Array.isArray(flashSale?.products) &&
    flashSale.products.length > 0
      ? flashSale.products
      : popularProducts;
  const flashSaleViewAllHref = flashSale?.is_active ? "/flash-sale" : "/products?is_popular=1";

  return (
    <div className="min-h-screen bg-[#fcfcfc] selection:bg-[#2b9d10] selection:text-white">
      <Header />

      <main>
        <Hero />

        <BannerSlider />

        <CategorySection />

        <NewArrivals initialProducts={featuredProducts} />

        <section className="container mx-auto px-4 py-8 md:py-16">
          <div className="bg-zinc-900 rounded-3xl md:rounded-[2.5rem] p-6 sm:p-10 md:p-12 relative overflow-hidden group">
            <div className="relative z-10 flex flex-col md:flex-row items-center justify-between gap-8 md:gap-12">
              <div className="text-center md:text-left space-y-4 md:space-y-6">
                <div className="inline-flex items-center gap-2 bg-[#2b9d10] text-white px-3 py-1.5 rounded-full font-bold text-[10px] uppercase tracking-wider">
                  <Zap size={12} className="fill-current" />{" "}
                  {settings?.flash_sale_badge || "Flash Sale Ending Soon"}
                </div>
                <h2 className="text-2xl sm:text-3xl md:text-5xl font-black text-white leading-tight">
                  {settings?.flash_sale_title1 || "Grab Your Deals"}{" "}
                  <br className="hidden sm:block" />
                  <span className="text-[#2b9d10]">
                    {settings?.flash_sale_title2 || "Before They're Gone!"}
                  </span>
                </h2>
                <div className="flex justify-center md:justify-start gap-3">
                  {[
                    { label: "DAYS", val: timeLeft.days },
                    { label: "HOURS", val: timeLeft.hours },
                    { label: "MINS", val: timeLeft.mins },
                    { label: "SECS", val: timeLeft.secs },
                  ].map((t) => (
                    <div
                      key={t.label}
                      className="flex flex-col items-center bg-white/10 rounded-xl p-3 w-16 md:w-20 border border-white/5"
                    >
                      <span className="text-xl md:text-2xl font-black text-white">
                        {t.val}
                      </span>
                      <span className="text-[8px] font-bold text-zinc-500 tracking-wider uppercase">
                        {t.label}
                      </span>
                    </div>
                  ))}
                </div>
                <div className="mt-4 flex justify-center md:justify-start">
                  <Link
                    href={flashSaleViewAllHref}
                    className="inline-flex items-center gap-2 bg-white text-zinc-900 px-5 py-2.5 rounded-full text-[11px] font-black tracking-[0.2em] uppercase hover:bg-[#2b9d10] hover:text-white transition-all duration-300 shadow-md shadow-black/20"
                  >
                    View All Flash Deals
                    <ArrowRight size={14} />
                  </Link>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4 w-full max-w-md">
                {loading ? (
                  <>
                    <ProductCardSkeleton />
                    <ProductCardSkeleton />
                  </>
                ) : (
                  flashSaleProducts.slice(0, 2).map((product) => (
                    <ProductCard key={product.id} product={product} />
                  ))
                )}
              </div>
            </div>
          </div>
        </section>

        <section className="container mx-auto px-4 py-12 md:py-20">
          <div className="flex items-center justify-between mb-8 md:mb-12">
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <span className="w-8 h-[2px] bg-[#2b9d10]" />
                <span className="text-[10px] font-black text-[#2b9d10] uppercase tracking-[0.3em]">
                  {settings?.featured_products_badge || "Featured"}
                </span>
              </div>
              <h2 className="text-3xl md:text-5xl font-black text-zinc-900 tracking-tight">
                {settings?.featured_products_title1 || "Our"}{" "}
                <span className="text-zinc-400">
                  {settings?.featured_products_title2 || "Products"}
                </span>
              </h2>
            </div>
            <Link
              href="/products?is_featured=1"
              className="hidden md:flex items-center gap-2 text-sm font-bold text-zinc-400 hover:text-[#2b9d10] transition-colors group"
            >
              {settings?.featured_products_view_all || "VIEW ALL"}{" "}
              <ArrowRight
                size={16}
                className="group-hover:translate-x-1 transition-transform"
              />
            </Link>
          </div>

          {loading ? (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-6">
              {[...Array(8)].map((_, i) => (
                <ProductCardSkeleton key={i} />
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-6">
              {featuredProducts.map((product) => (
                <ProductCard key={product.id} product={product} />
              ))}
            </div>
          )}

          <div className="mt-8 flex md:hidden justify-center">
            <Link
              href="/products?is_featured=1"
              className="flex items-center gap-3 bg-zinc-100 px-8 py-3 rounded-xl font-black text-[10px] tracking-widest hover:bg-[#2b9d10] hover:text-white transition-all duration-500 w-full justify-center"
            >
              {settings?.featured_products_view_all || "VIEW ALL PRODUCTS"}{" "}
              <ArrowRight size={16} />
            </Link>
          </div>
        </section>

        <CouponSection />

        <ReviewSection />

        <section className="container mx-auto px-4 py-12 md:py-20">
          <div className="bg-zinc-900 rounded-[2rem] md:rounded-[3rem] p-8 md:p-16 flex flex-col lg:flex-row items-center justify-between overflow-hidden relative">
            <div className="absolute -top-24 -right-10 w-64 h-64 bg-[#2b9d10]/10 rounded-full blur-3xl" />
            <div className="absolute -bottom-24 -left-10 w-72 h-72 bg-emerald-500/10 rounded-full blur-3xl" />

            <div className="relative z-10 space-y-6 max-w-xl">
              <div className="inline-flex items-center gap-2 bg-white/5 text-emerald-300 px-3 py-1.5 rounded-full text-[10px] font-black tracking-[0.25em] uppercase">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
                {settings?.mobile_badge || "Mobile App"}
              </div>

              <h2 className="text-3xl md:text-5xl font-black text-white leading-tight">
                {settings?.mobile_title1 || "Get SmartGrocery"}{" "}
                <span className="text-emerald-400">
                  {settings?.mobile_title2 || "on Your Phone"}
                </span>
              </h2>

              <p className="text-zinc-300 text-sm md:text-base font-medium max-w-md">
                {settings?.mobile_description ||
                  "Experience grocery shopping like never before with instant checkout, real-time tracking, and personalized recommendations."}
              </p>

              <div className="flex flex-wrap gap-3">
                {settings?.play_store_link && (
                  <a
                    href={settings.play_store_link}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-3 px-4 py-2.5 bg-white rounded-2xl text-xs font-black text-zinc-900 tracking-[0.18em] uppercase shadow-md hover:bg-emerald-50 transition"
                  >
                    <i className="fab fa-google-play text-lg text-emerald-500" />
                    <span className="text-left leading-tight">
                      <span className="block text-[9px] text-zinc-500 font-semibold">
                        GET IT ON
                      </span>
                      <span className="block text-[11px]">
                        {settings.play_store_btn_text || "Google Play"}
                      </span>
                    </span>
                  </a>
                )}

                {settings?.app_store_link && (
                  <a
                    href={settings.app_store_link}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-3 px-4 py-2.5 bg-white rounded-2xl text-xs font-black text-zinc-900 tracking-[0.18em] uppercase shadow-md hover:bg-zinc-50 transition"
                  >
                    <i className="fab fa-apple text-xl" />
                    <span className="text-left leading-tight">
                      <span className="block text-[9px] text-zinc-500 font-semibold">
                        DOWNLOAD ON THE
                      </span>
                      <span className="block text-[11px]">
                        {settings.app_store_btn_text || "App Store"}
                      </span>
                    </span>
                  </a>
                )}
              </div>

              <div className="flex items-center gap-4 pt-2">
                <div className="flex items-center -space-x-2">
                  <div className="w-8 h-8 rounded-full bg-emerald-500 flex items-center justify-center text-xs font-black text-white ring-2 ring-zinc-900">
                    <span>AK</span>
                  </div>
                  <div className="w-8 h-8 rounded-full bg-amber-400 flex items-center justify-center text-xs font-black text-white ring-2 ring-zinc-900">
                    <span>SR</span>
                  </div>
                  <div className="w-8 h-8 rounded-full bg-sky-400 flex items-center justify-center text-xs font-black text-white ring-2 ring-zinc-900">
                    <span>MJ</span>
                  </div>
                </div>
                <div className="text-xs text-zinc-300">
                  <span className="font-semibold text-white">
                    10K+ premium users
                  </span>{" "}
                  trust SmartGrocery for weekly grocery runs.
                </div>
              </div>
            </div>

            <div className="relative z-10 mt-10 lg:mt-0">
              <div className="relative w-[260px] sm:w-[320px] md:w-[360px] aspect-[9/19] mx-auto">
                <div className="absolute inset-0 bg-gradient-to-b from-emerald-400/20 to-zinc-900/80 rounded-[2.2rem] blur-3xl" />

                <div className="relative bg-zinc-950 rounded-[2.4rem] border border-zinc-800/80 shadow-2xl shadow-emerald-500/10 overflow-hidden">
                  <div className="absolute inset-0 bg-[radial-gradient(circle_at_top,_#22c55e33,_transparent_55%),_radial-gradient(circle_at_bottom,_#22c55e22,_transparent_55%)]" />

                  <div className="relative z-10 flex flex-col h-full">
                    <div className="flex items-center justify-between px-5 pt-4">
                      <div className="w-10 h-1 bg-zinc-800 rounded-full mx-auto" />
                    </div>

                    <div className="px-6 pt-5 pb-4">
                      <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-emerald-500/10 border border-emerald-500/40">
                        <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
                        <span className="text-[9px] font-semibold tracking-[0.28em] uppercase text-emerald-200">
                          Live Orders
                        </span>
                      </div>

                      <h3 className="mt-4 text-xl font-black text-white leading-tight">
                        Your groceries,{" "}
                        <span className="text-emerald-400">on auto-pilot.</span>
                      </h3>

                      <p className="mt-2 text-[11px] text-zinc-400 font-medium">
                        Track deliveries, manage subscriptions and re-order
                        favorites in seconds.
                      </p>
                    </div>

                    <div className="flex-1 px-3 space-y-3 pb-4">
                      {[
                        {
                          title: "Ultra-fast delivery",
                          subtitle: "Under 30 mins guarantee",
                          icon: settings?.feature1_icon || "🚀",
                          color: "from-emerald-500/80 to-emerald-400/80",
                        },
                        {
                          title: "Encrypted payments",
                          subtitle: "Backed by bank-grade security",
                          icon: settings?.feature2_icon || "🛡️",
                          color: "from-sky-500/80 to-blue-500/80",
                        },
                        {
                          title: "Concierge support",
                          subtitle: "Priority 24/7 customer care",
                          icon: settings?.feature3_icon || "💎",
                          color: "from-amber-400/80 to-orange-500/80",
                        },
                      ].map((card, index) => (
                        <div
                          key={index}
                          className="flex items-center gap-3 p-2 rounded-2xl bg-zinc-900/80 border border-zinc-800/80"
                        >
                          <div className="w-10 h-10 rounded-2xl bg-gradient-to-br from-zinc-800 to-zinc-900 flex items-center justify-center text-lg">
                            {renderIcon(card.icon, "text-lg")}
                          </div>
                          <div className="flex-1">
                            <p className="text-[11px] font-semibold text-white">
                              {card.title}
                            </p>
                            <p className="text-[10px] text-zinc-400">
                              {card.subtitle}
                            </p>
                          </div>
                        </div>
                      ))}
                    </div>

                    <div className="px-5 pb-4">
                      <div className="flex items-center justify-between text-[10px] text-zinc-500">
                        <span>Designed for SmartGrocery Premium</span>
                        <span className="inline-flex items-center gap-1 text-emerald-300">
                          <span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
                          v2.1.0
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        <section className="py-12 md:py-16 border-t border-zinc-50">
          <div className="container mx-auto px-4">
            <div className="flex flex-col lg:flex-row items-center gap-10">
              <div className="flex-1 space-y-4">
                <div className="inline-flex items-center gap-2 bg-emerald-50 text-emerald-700 px-3 py-1.5 rounded-full text-[10px] font-black tracking-[0.25em] uppercase">
                  <Tag size={12} />{" "}
                  <span>
                    {settings?.coupon_section_badge || "Exclusive Offers"}
                  </span>
                </div>
                <h2 className="text-3xl md:text-5xl font-black text-zinc-900 leading-tight">
                  {settings?.coupon_section_title1 || "Save Big with"}{" "}
                  <span className="text-emerald-500">
                    {settings?.coupon_section_title2 || "Premium Coupons"}
                  </span>
                </h2>
                <p className="text-zinc-500 font-medium">
                  {settings?.coupon_section_description ||
                    "Use these exclusive discount codes at checkout to enjoy premium savings on your favorite organic groceries."}
                </p>
                <ul className="space-y-2 text-sm text-zinc-600">
                  <li className="flex items-center gap-2">
                    <span className="w-5 h-5 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center text-[10px]">
                      ✓
                    </span>
                    Weekly app-only deals for premium members
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="w-5 h-5 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center text-[10px]">
                      ✓
                    </span>
                    Stackable coupons on select categories
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="w-5 h-5 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center text-[10px]">
                      ✓
                    </span>
                    Early access to flash sales and limited-time offers
                  </li>
                </ul>
              </div>

              <div className="flex-1 w-full">
                <div className="bg-gradient-to-br from-emerald-500 to-emerald-600 rounded-3xl p-6 md:p-8 text-white shadow-xl relative overflow-hidden">
                  <div className="absolute -right-16 -top-16 w-56 h-56 bg-emerald-400/30 rounded-full blur-3xl" />
                  <div className="absolute -left-10 -bottom-10 w-40 h-40 bg-emerald-700/40 rounded-full blur-3xl" />

                  <div className="relative z-10 space-y-4">
                    <div className="inline-flex items-center gap-2 bg-white/10 px-3 py-1 rounded-full text-[10px] font-semibold tracking-[0.25em] uppercase">
                      <span className="w-1.5 h-1.5 rounded-full bg-emerald-300 animate-pulse" />
                      LIMITED TIME BONUS
                    </div>

                    <h3 className="text-2xl md:text-3xl font-black leading-tight">
                      Get up to{" "}
                      <span className="text-yellow-300">50% off</span> on your
                      first 3 orders.
                    </h3>

                    <p className="text-sm text-emerald-50/90">
                      Apply these premium codes at checkout and watch your cart
                      total drop instantly.
                    </p>

                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mt-4">
                      {[
                        {
                          code: "SMART10",
                          label: "On orders over ৳1000",
                          percent: "-10%",
                        },
                        {
                          code: "ELITE20",
                          label: "For premium users only",
                          percent: "-20%",
                        },
                        {
                          code: "FRESH30",
                          label: "On select fresh items",
                          percent: "-30%",
                        },
                      ].map((coupon) => (
                        <div
                          key={coupon.code}
                          className="bg-white/5 rounded-2xl p-3 border border-white/10 flex flex-col gap-2"
                        >
                          <div className="flex items-center justify-between">
                            <span className="text-xs font-semibold tracking-[0.18em] uppercase text-emerald-100">
                              Coupon
                            </span>
                            <span className="text-xs font-bold text-yellow-200">
                              {coupon.percent}
                            </span>
                          </div>
                          <div className="flex items-center justify-between gap-2">
                            <code className="px-2 py-1 rounded-xl bg-black/30 text-xs font-mono tracking-[0.22em]">
                              {coupon.code}
                            </code>
                            <button className="text-[10px] font-semibold uppercase tracking-[0.18em] bg-white/10 px-2 py-1 rounded-lg hover:bg-white/20 transition">
                              Copy
                            </button>
                          </div>
                          <p className="text-[10px] text-emerald-50/80">
                            {coupon.label}
                          </p>
                        </div>
                      ))}
                    </div>

                    <p className="text-[10px] text-emerald-100/80 mt-2">
                      *Terms apply. Coupons valid for a limited period and
                      cannot be combined with some promotional offers.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        <section className="py-12 md:py-16 border-b border-zinc-50">
          <div className="container mx-auto px-4 text-center">
            <p className="text-zinc-400 font-bold text-[10px] uppercase tracking-widest mb-8">
              {settings?.featured_brands_label || "TRUSTED BY LEADING BRANDS"}
            </p>
            <div className="flex flex-wrap justify-center items-center gap-8 md:gap-16 opacity-40">
              {(settings?.featured_brands ||
                "Forbes, TechCrunch, The Verge, Wired, Vogue")
                .split(",")
                .map((brand: string) => (
                  <span
                    key={brand.trim()}
                    className="text-lg md:text-2xl font-black text-zinc-900 tracking-tight"
                  >
                    {brand.trim()}
                  </span>
                ))}
            </div>
          </div>
        </section>
      </main>

      <Footer />
    </div>
  );
}
