"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 { Suspense } from "react";
import { Search, Zap } from "lucide-react";

function FlashSaleContent() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [lastPage, setLastPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState("");

  useEffect(() => {
    const fetchFlashSale = async () => {
      try {
        setLoading(true);
        const params: any = {
          page,
          is_flash_sale: true,
        };

        if (searchQuery) {
          params.search = searchQuery;
        }

        const response = await api.getProducts(params);
        if (response.data) {
          setProducts(response.data);
          const currentPage = response.current_page || (response as any).currentPage || page;
          const resolvedLastPage = response.last_page || (response as any).lastPage || page;
          if (currentPage !== page) {
            setPage(currentPage);
          }
          setLastPage(resolvedLastPage);
        }
      } catch (error) {
        console.error("Failed to fetch flash sale products:", error);
      } finally {
        setLoading(false);
      }
    };

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

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

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

  const getPageNumbers = () => {
    const pages: number[] = [];
    const start = Math.max(1, page - 2);
    const end = Math.min(totalPages, page + 2);
    for (let i = start; i <= end; i += 1) pages.push(i);
    return pages;
  };

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

      <section className="bg-white border-b border-zinc-100 py-12 md:py-20 relative overflow-hidden">
        <div className="absolute top-0 right-0 w-1/3 h-full bg-emerald-50/60 skew-x-12 translate-x-1/2 -z-0" />
        <div className="absolute bottom-0 left-0 w-64 h-64 bg-lime-50/60 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-emerald-50 text-emerald-600 rounded-full border border-emerald-100 shadow-sm"
              >
                <Zap size={14} className="fill-emerald-600" />
                <span className="text-[10px] font-black uppercase tracking-[0.2em]">
                  Flash 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"
              >
                Today&apos;s
                <span className="text-emerald-500 italic"> Flash</span> Sale
              </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"
              >
                Limited-time discounts on fresh groceries. Stock up before the timer runs out.
              </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-2 bg-white border border-zinc-100 rounded-2xl px-5 py-4 shadow-sm"
            >
              <div className="w-10 h-10 rounded-xl bg-emerald-50 flex items-center justify-center text-emerald-600">
                <Zap size={16} />
              </div>
              <div className="space-y-1">
                <div className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-400">
                  Limited Time
                </div>
                <div className="text-sm font-black text-zinc-900">Flash Sale Picks</div>
              </div>
            </motion.div>
          </div>
        </div>
      </section>

      <main className="container mx-auto px-4 py-12 md:py-20">
        <div className="flex flex-col gap-12">
          <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 flash sale products..."
                className="w-full pl-14 pr-6 py-4 bg-white border border-zinc-100 rounded-[1.5rem] focus:outline-none focus:border-emerald-500/30 focus:ring-4 focus:ring-emerald-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-emerald-500">{products.length}</span>
              </div>
            </div>
          </div>

          <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="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 md:gap-10">
                  <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>

                {showPagination && (
                  <div className="mt-16 flex items-center justify-center gap-3">
                    <button
                      onClick={() => setPage((prev) => Math.max(1, prev - 1))}
                      disabled={page === 1 || loading}
                      className="px-5 py-3 rounded-xl border border-zinc-200 bg-white text-zinc-600 text-[11px] font-black uppercase tracking-[0.2em] hover:bg-zinc-50 disabled:opacity-40 disabled:cursor-not-allowed"
                    >
                      Prev
                    </button>
                    <div className="flex items-center gap-2">
                      {getPageNumbers().map((p) => (
                        <button
                          key={p}
                          onClick={() => setPage(p)}
                          disabled={loading}
                          className={`w-10 h-10 rounded-xl text-[11px] font-black ${
                            p === page
                              ? "bg-emerald-500 text-white shadow-md shadow-emerald-500/30"
                              : "bg-white border border-zinc-200 text-zinc-600 hover:bg-zinc-50"
                          }`}
                        >
                          {p}
                        </button>
                      ))}
                    </div>
                    <button
                      onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
                      disabled={page === totalPages || loading}
                      className="px-5 py-3 rounded-xl border border-zinc-200 bg-white text-zinc-600 text-[11px] font-black uppercase tracking-[0.2em] hover:bg-zinc-50 disabled:opacity-40 disabled:cursor-not-allowed"
                    >
                      Next
                    </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-emerald-50 rounded-full flex items-center justify-center mx-auto mb-8">
                  <Zap size={32} className="text-emerald-300" />
                </div>
                <h2 className="text-2xl font-black text-zinc-900 mb-3 uppercase tracking-tight">
                  No Flash Sale Items
                </h2>
                <p className="text-zinc-500 max-w-lg mx-auto">
                  There are currently no active flash sale offers. Check back soon for limited-time
                  discounts on your favorite groceries.
                </p>
              </motion.div>
            )}
          </div>
        </div>
      </main>

      <Footer />
    </div>
  );
}

export default function FlashSalePage() {
  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>
      }
    >
      <FlashSaleContent />
    </Suspense>
  );
}
