"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 Home() {
  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?.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();
  }, []);

  // Timer for Flash Sale
  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} />

        {/* Flash Sale Section */}
        <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>

        {/* Featured Products */}
        <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 />

        {/* App Promo Section */}
        <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="relative z-10 text-white max-w-xl text-center lg:text-left">
                <div className="inline-block bg-[#2b9d10] text-[10px] font-bold uppercase tracking-wider px-4 py-1.5 rounded-full mb-6">
                  {settings?.mobile_badge || "Mobile Experience"}
                </div>
                <h2 className="text-3xl md:text-5xl font-black mb-6 leading-tight">
                  {settings?.mobile_title1 || "The Whole Store"} <br />
                  <span className="text-[#2b9d10]">
                    {settings?.mobile_title2 || "In Your Pocket"}
                  </span>
                </h2>
                <p className="text-zinc-400 text-sm md:text-lg mb-10 font-medium leading-relaxed">
                  {settings?.mobile_description ||
                    `Get the ${(settings?.site_name || "Ready Grocery")} app for exclusive early access to deals, personalized recommendations, and real-time tracking.`}
                </p>
                
                <div className="flex flex-col sm:flex-row justify-center lg:justify-start gap-4">
                   <Link 
                     href={settings?.app_store_link || "#"}
                     className="bg-white text-black px-6 py-3 rounded-xl flex items-center gap-3 hover:bg-zinc-100 transition-all justify-center"
                   >
                      <div className="text-2xl">🍎</div>
                      <div className="text-left leading-none">
                         <p className="text-[9px] font-bold uppercase text-zinc-400 mb-1">App Store</p>
                         <p className="text-base font-black">{settings?.app_store_btn_text || "Download Now"}</p>
                      </div>
                   </Link>
                   <Link 
                     href={settings?.play_store_link || "#"}
                     className="bg-white text-black px-6 py-3 rounded-xl flex items-center gap-3 hover:bg-zinc-100 transition-all justify-center"
                   >
                      <div className="text-2xl">🤖</div>
                      <div className="text-left leading-none">
                         <p className="text-[9px] font-bold uppercase text-zinc-400 mb-1">Google Play</p>
                         <p className="text-base font-black">{settings?.play_store_btn_text || "Get it Today"}</p>
                      </div>
                   </Link>
                </div>
             </div>

             <div className="mt-12 lg:mt-0 relative z-10 hidden lg:block">
                <motion.div 
                  animate={{ y: [0, -15, 0] }}
                  transition={{ duration: 4, repeat: Infinity, ease: "easeInOut" }}
                  className="w-64 h-[500px] bg-zinc-800 rounded-[2.5rem] border-[10px] border-zinc-700 shadow-2xl relative overflow-hidden"
                >
                   <div className="absolute top-0 w-full h-8 bg-zinc-700 flex justify-center items-center">
                      <div className="w-12 h-1 bg-zinc-600 rounded-full" />
                   </div>
                   <div className="p-5 pt-12 space-y-4">
                      <div className="w-10 h-10 bg-[#2b9d10] rounded-xl flex items-center justify-center">
                         <div className="w-5 h-5 border-2 border-white rounded-md" />
                      </div>
                      <div className="space-y-2">
                         <div className="h-4 bg-zinc-700 rounded-full w-3/4" />
                         <div className="h-3 bg-zinc-700 rounded-full w-full" />
                      </div>
                      <div className="grid grid-cols-2 gap-2 pt-2">
                         <div className="h-24 bg-zinc-700 rounded-2xl" />
                         <div className="h-24 bg-zinc-700 rounded-2xl" />
                      </div>
                      <div className="h-28 bg-zinc-700/50 rounded-2xl" />
                   </div>
                </motion.div>
             </div>
          </div>
        </section>

        {/* Features Section */}
        <section className="container mx-auto px-4 py-12 md:py-20">
           <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8 md:gap-10">
              {[
                { 
                  title: settings?.feature1_title || "Fast Delivery", 
                  desc: settings?.feature1_desc || "Under 30 mins guarantee", 
                  icon: settings?.feature1_icon || "🚀", 
                  color: "bg-emerald-50", 
                  text: "text-emerald-600" 
                },
                { 
                  title: settings?.feature2_title || "Secure Payment", 
                  desc: settings?.feature2_desc || "100% encrypted payments", 
                  icon: settings?.feature2_icon || "🛡️", 
                  color: "bg-blue-50", 
                  text: "text-blue-600" 
                },
                { 
                  title: settings?.feature3_title || "24/7 Support", 
                  desc: settings?.feature3_desc || "Dedicated concierge team", 
                  icon: settings?.feature3_icon || "💎", 
                  color: "bg-amber-50", 
                  text: "text-amber-600" 
                },
                { 
                  title: settings?.feature4_title || "Farm Fresh", 
                  desc: settings?.feature4_desc || "100% farm fresh products", 
                  icon: settings?.feature4_icon || "🌿", 
                  color: "bg-rose-50", 
                  text: "text-rose-600" 
                },
              ].map((feature, index) => (
                <div 
                  key={index}
                  className="flex flex-col items-center text-center p-6 rounded-2xl bg-white border border-zinc-100 hover:border-[#2b9d10]/20 transition-all group"
                >
                  <div className={`w-14 h-14 ${feature.color} ${feature.text} rounded-xl flex items-center justify-center text-2xl mb-4 group-hover:scale-110 transition-transform`}>
                    {renderIcon(feature.icon)}
                  </div>
                  <h4 className="font-bold text-zinc-900 text-lg mb-2">{feature.title}</h4>
                  <p className="text-zinc-500 text-sm font-medium">{feature.desc}</p>
                </div>
              ))}
           </div>
        </section>

        {/* Testimonials Section */}
        <section className="bg-zinc-50 py-16 md:py-24">
          <div className="container mx-auto px-4">
            <div className="text-center max-w-2xl mx-auto mb-12 md:mb-16">
              <div className="inline-block bg-[#2b9d10]/10 text-[#2b9d10] text-[10px] font-bold uppercase tracking-wider px-4 py-1.5 rounded-full mb-4">
                {settings?.testimonial_badge || "Wall of Love"}
              </div>
              <h2 className="text-3xl md:text-5xl font-black text-zinc-900 tracking-tight">
                {settings?.testimonial_title1 || "Trusted by"} <span className="text-[#2b9d10]">{settings?.testimonial_title2 || "Thousands"}</span>
              </h2>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 md:gap-8">
              {[1, 2, 3].map((i) => {
                const name = settings?.[`testimonial${i}_name` as keyof typeof settings] as string;
                const role = settings?.[`testimonial${i}_role` as keyof typeof settings] as string;
                const content = settings?.[`testimonial${i}_content` as keyof typeof settings] as string;
                const avatar = settings?.[`testimonial${i}_avatar` as keyof typeof settings] as string;

                const defaultTestimonials = [
                  { 
                    name: "Sarah Johnson", 
                    role: "Nutritionist", 
                    content: "The quality of organic produce here is unmatched. It's like having a premium farmer's market right at my fingertips.", 
                    avatar: "👩‍⚕️"
                  },
                  { 
                    name: "David Chen", 
                    role: "Home Chef", 
                    content: "Delivery is always on time, and the packaging is eco-friendly. Truly a 5-star experience every order.", 
                    avatar: "👨‍🍳"
                  },
                  { 
                    name: "Emily Rodriguez", 
                    role: "Busy Mom", 
                    content: "The app is so intuitive! I can finish my weekly grocery shopping in under 5 minutes. A total lifesaver.", 
                    avatar: "👩‍💼"
                  }
                ];

                const currentTestimonial = {
                  name: name || defaultTestimonials[i-1].name,
                  role: role || defaultTestimonials[i-1].role,
                  content: content || defaultTestimonials[i-1].content,
                  avatar: avatar || defaultTestimonials[i-1].avatar
                };

                return (
                  <div 
                    key={i}
                    className="bg-white p-8 rounded-2xl border border-zinc-100 shadow-sm flex flex-col h-full"
                  >
                    <div className="flex gap-1 mb-4 text-yellow-400">
                      {[...Array(5)].map((_, starIdx) => (
                        <span key={starIdx} className="text-xs">★</span>
                      ))}
                    </div>
                    <p className="text-zinc-600 font-medium text-base leading-relaxed mb-6 flex-grow">
                      "{currentTestimonial.content}"
                    </p>
                    <div className="flex items-center gap-4 pt-6 border-t border-zinc-50">
                      <div className="w-10 h-10 bg-zinc-50 rounded-full flex items-center justify-center text-xl overflow-hidden border border-zinc-100">
                        {renderIcon(currentTestimonial.avatar)}
                      </div>
                      <div>
                        <h4 className="font-bold text-zinc-900 leading-none mb-1 text-sm">{currentTestimonial.name}</h4>
                        <p className="text-zinc-400 text-[10px] font-bold uppercase tracking-wider">{currentTestimonial.role}</p>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </section>

        {/* Trust 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>
  );
}
