"use client";

import { useState, useEffect } from "react";
import { api } from "@/lib/api";
import { Product } from "@/types";
import ProductCard from "@/components/product/ProductCard";
import { motion, AnimatePresence } from "framer-motion";
import ProductCardSkeleton from "@/components/product/ProductCardSkeleton";
import Header from "@/components/layout/Header";
import Footer from "@/components/layout/Footer";
import { getImageUrl } from "@/lib/api";
import Image from "next/image";
import { Skeleton } from "@/components/ui/Skeleton";
import BannerSlider from "@/components/home/BannerSlider";
import { 
  Zap, 
  ArrowRight,
  Gift,
  Sparkles,
  Search,
  LayoutGrid,
  List
} from "lucide-react";
import { Suspense } from "react";

function SpecialOffersContent() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [viewType, setViewType] = useState<'grid' | 'list'>('grid');
  const [searchQuery, setSearchQuery] = useState("");
  const [settings, setSettings] = useState<any>(null);
  const [settingsLoading, setSettingsLoading] = useState(true);
  const [bannerIndex, setBannerIndex] = useState(0);

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const res = await api.getSettings();
        setSettings(res.data || {});
      } catch (_) {
      } finally {
        setSettingsLoading(false);
      }
    };
    loadSettings();
  }, []);

  useEffect(() => {
    const isFallback = !settings?.special_offers_banner;
    if (!isFallback) return;
    const t = setInterval(() => {
      setBannerIndex((prev) => (prev + 1) % 5);
    }, 4500);
    return () => clearInterval(t);
  }, [settings?.special_offers_banner]);

  useEffect(() => {
    const fetchSpecialOffers = async () => {
      try {
        setLoading(true);
        const params: any = { 
          page, 
          is_special_offer: true 
        };
        
        if (searchQuery) {
          params.search = searchQuery;
        }
        
        const response = await api.getProducts(params);
        if (response.data) {
          if (page === 1) {
            setProducts(response.data);
          } else {
            setProducts((prev) => [...prev, ...response.data]);
          }
          const currentPage = response.current_page || (response as any).currentPage || page;
          const lastPage = response.last_page || (response as any).lastPage || page;
          setHasMore(currentPage < lastPage);
        }
      } catch (error) {
        console.error("Failed to fetch special offers:", error);
      } finally {
        setLoading(false);
      }
    };

    const timer = setTimeout(() => {
      fetchSpecialOffers();
    }, 300);

    return () => clearTimeout(timer);
  }, [page, searchQuery]);

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    setPage(1);
    setProducts([]);
  };

  const loadMore = () => {
    if (!loading && hasMore) {
      setPage((prev) => prev + 1);
    }
  };

  return (
    <div className="min-h-screen bg-[#fcfcfc] selection:bg-rose-500 selection:text-white">
      <Header />
      <BannerSlider source="special_offers" />

      {/* Premium Hero Header */}
      <section className="bg-white border-b border-zinc-100 py-12 md:py-20 relative overflow-hidden">
        {/* Background Accents */}
        <div className="absolute top-0 right-0 w-1/3 h-full bg-rose-50/50 skew-x-12 translate-x-1/2 -z-0" />
        <div className="absolute bottom-0 left-0 w-64 h-64 bg-amber-50/50 rounded-full -translate-x-1/2 translate-y-1/2 blur-3xl -z-0" />

        <div className="container mx-auto px-4 relative z-10">
          <div className="flex flex-col lg:flex-row lg:items-end justify-between gap-8">
            <div className="space-y-4 max-w-2xl">
              <motion.div 
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                className="inline-flex items-center gap-2 px-4 py-1.5 bg-rose-50 text-rose-600 rounded-full border border-rose-100 shadow-sm"
              >
                <Zap size={14} className="fill-rose-600" />
                <span className="text-[10px] font-black uppercase tracking-[0.2em]">Exclusive Deals</span>
              </motion.div>
              
              <motion.h1 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1 }}
                className="text-4xl md:text-6xl font-black text-zinc-900 tracking-tight"
              >
                Special <span className="text-rose-500 italic">Offers</span> & <br />
                Limited <span className="text-amber-500">Deals</span>
              </motion.h1>
              
              <motion.p 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.2 }}
                className="text-zinc-500 text-base md:text-lg font-medium leading-relaxed"
              >
                Unbeatable prices on your favorite premium groceries. 
                Handpicked quality, specifically discounted for our valued members.
              </motion.p>
            </div>
            
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 0.3 }}
              className="flex items-center gap-1 bg-zinc-50 p-1.5 rounded-2xl border border-zinc-100 shadow-inner"
            >
              <button 
                onClick={() => setViewType('grid')}
                className={`flex items-center gap-2 px-6 py-3 rounded-xl transition-all font-black text-[10px] tracking-wider ${viewType === 'grid' ? 'bg-white text-zinc-900 shadow-md border border-zinc-100' : 'text-zinc-400 hover:text-zinc-600'}`}
              >
                <LayoutGrid size={14} /> GRID
              </button>
              <button 
                onClick={() => setViewType('list')}
                className={`flex items-center gap-2 px-6 py-3 rounded-xl transition-all font-black text-[10px] tracking-wider ${viewType === 'list' ? 'bg-white text-zinc-900 shadow-md border border-zinc-100' : 'text-zinc-400 hover:text-zinc-600'}`}
              >
                <List size={14} /> LIST
              </button>
            </motion.div>
          </div>
        </div>
      </section>

      <main className="container mx-auto px-4 py-12 md:py-20">
        <div className="flex flex-col gap-12">
          {/* Search and Filters */}
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-8">
            <div className="flex-1 relative max-w-xl">
              <Search className="absolute left-5 top-1/2 -translate-y-1/2 text-zinc-300" size={18} />
              <input 
                type="text" 
                value={searchQuery}
                onChange={handleSearchChange}
                placeholder="Search special offers..."
                className="w-full pl-14 pr-6 py-4 bg-white border border-zinc-100 rounded-[1.5rem] focus:outline-none focus:border-rose-500/30 focus:ring-4 focus:ring-rose-500/5 transition-all text-sm font-medium shadow-sm"
              />
            </div>
            
            <div className="flex items-center gap-6">
              <div className="flex items-baseline gap-2">
                <span className="text-zinc-400 text-[11px] font-black uppercase tracking-widest">Available Items</span>
                <span className="text-2xl font-black text-rose-500">{products.length}</span>
              </div>
              <div className="h-8 w-px bg-zinc-100" />
              <div className="flex items-center gap-2 px-4 py-2 bg-amber-50 rounded-xl border border-amber-100">
                <Sparkles size={14} className="text-amber-500" />
                <span className="text-[10px] font-bold text-amber-700 uppercase tracking-wider">Updates Daily</span>
              </div>
            </div>
          </div>

          {/* Product Grid Area */}
          <div className="min-h-[400px]">
            {loading && page === 1 ? (
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 md:gap-10">
                {[...Array(8)].map((_, i) => (
                  <ProductCardSkeleton key={i} />
                ))}
              </div>
            ) : products.length > 0 ? (
              <>
                <div className={viewType === 'grid' 
                  ? "grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 md:gap-10" 
                  : "flex flex-col gap-8"
                }>
                  <AnimatePresence mode="popLayout">
                    {products.map((product, index) => (
                      <motion.div
                        key={product.id}
                        layout
                        initial={{ opacity: 0, scale: 0.9 }}
                        animate={{ opacity: 1, scale: 1 }}
                        exit={{ opacity: 0, scale: 0.9 }}
                        transition={{ duration: 0.4, delay: index * 0.05 }}
                        className="relative group"
                      >
                        <ProductCard product={product} />
                      </motion.div>
                    ))}
                  </AnimatePresence>
                </div>

                {hasMore && (
                  <div className="mt-20 text-center">
                    <button
                      onClick={loadMore}
                      disabled={loading}
                      className="bg-zinc-900 text-white px-12 py-5 rounded-[2rem] font-black text-[11px] uppercase tracking-[0.2em] hover:bg-rose-500 transition-all duration-500 disabled:opacity-50 inline-flex items-center gap-4 shadow-2xl shadow-zinc-200"
                    >
                      {loading ? (
                        <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                      ) : (
                        <>Discover More Deals <ArrowRight size={14} /></>
                      )}
                    </button>
                  </div>
                )}
              </>
            ) : (
              <motion.div 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="text-center py-32 bg-white rounded-[2.5rem] border border-zinc-100 px-8 shadow-sm"
              >
                <div className="w-24 h-24 bg-rose-50 rounded-full flex items-center justify-center mx-auto mb-8">
                  <Gift size={32} className="text-rose-200" />
                </div>
                <h2 className="text-2xl font-black text-zinc-900 mb-3 uppercase tracking-tight">No Special Offers</h2>
                <p className="text-zinc-400 text-base font-medium mb-10 max-w-sm mx-auto">We're currently preparing new exclusive deals. Please check back later for exciting discounts!</p>
                <button 
                  onClick={() => window.location.href = '/products'}
                  className="bg-zinc-900 text-white px-10 py-4 rounded-2xl font-black text-[11px] uppercase tracking-widest hover:bg-rose-500 transition-all shadow-xl"
                >
                  Explore All Products
                </button>
              </motion.div>
            )}
          </div>
        </div>
      </main>
      
      <Footer />
    </div>
  );
}

export default function SpecialOffersPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-[#fcfcfc]">
        <Header />
        <main className="container mx-auto px-4 py-20">
          <div className="space-y-12">
            <div className="space-y-4">
              <div className="h-4 w-32 bg-zinc-100 animate-pulse rounded-full" />
              <div className="h-16 w-1/2 bg-zinc-100 animate-pulse rounded-2xl" />
              <div className="h-20 w-2/3 bg-zinc-100 animate-pulse rounded-2xl" />
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
              {[...Array(8)].map((_, i) => (
                <ProductCardSkeleton key={i} />
              ))}
            </div>
          </div>
        </main>
      </div>
    }>
      <SpecialOffersContent />
    </Suspense>
  );
}
