"use client";

import { useState, useEffect } from "react";
import { api } from "@/lib/api";
import { Product } from "@/types";
import ProductCard from "@/components/product/ProductCard";
import ProductCardSkeleton from "@/components/product/ProductCardSkeleton";
import Header from "@/components/layout/Header";
import Footer from "@/components/layout/Footer";
import { motion, AnimatePresence } from "framer-motion";
import { Search, LayoutGrid, List, Sparkles, ArrowRight } from "lucide-react";
import { Suspense } from "react";

function NewArrivalsContent() {
  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("");

  useEffect(() => {
    const fetchNewArrivals = async () => {
      try {
        setLoading(true);
        const params: any = { page, is_featured: 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) {
        setHasMore(false);
      } finally {
        setLoading(false);
      }
    };

    const timer = setTimeout(() => {
      fetchNewArrivals();
    }, 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-[#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"
              >
                <Sparkles size={14} className="fill-emerald-600" />
                <span className="text-[10px] font-black uppercase tracking-[0.2em]">
                  New Drops
                </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"
              >
                Fresh <span className="text-emerald-500 italic">New</span> Arrivals
              </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"
              >
                Explore the latest additions to the store, curated for freshness and quality.
              </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-4 py-2 rounded-lg transition-all font-bold text-[10px] tracking-wider ${viewType === "grid" ? "bg-white text-zinc-900 shadow-sm border border-zinc-100" : "text-zinc-400 hover:text-zinc-600"}`}
              >
                <LayoutGrid size={12} /> GRID
              </button>
              <button
                onClick={() => setViewType("list")}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all font-bold text-[10px] tracking-wider ${viewType === "list" ? "bg-white text-zinc-900 shadow-sm border border-zinc-100" : "text-zinc-400 hover:text-zinc-600"}`}
              >
                <List size={12} /> 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-10">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
            <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 new arrivals..."
                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">
                  Products
                </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={
                    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.96 }}
                        animate={{ opacity: 1, scale: 1 }}
                        exit={{ opacity: 0, scale: 0.96 }}
                        transition={{ duration: 0.4, delay: index * 0.04 }}
                        className="relative group"
                      >
                        <ProductCard product={product} />
                      </motion.div>
                    ))}
                  </AnimatePresence>
                </div>

                {hasMore && (
                  <div className="mt-16 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-emerald-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" />
                      ) : (
                        <>
                          Load More <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-emerald-50 rounded-full flex items-center justify-center mx-auto mb-8">
                  <Sparkles size={32} className="text-emerald-200" />
                </div>
                <h2 className="text-2xl font-black text-zinc-900 mb-3 uppercase tracking-tight">
                  No New Arrivals
                </h2>
                <p className="text-zinc-400 text-base font-medium mb-10 max-w-sm mx-auto">
                  Fresh items will appear here as soon as they drop.
                </p>
              </motion.div>
            )}
          </div>
        </div>
      </main>

      <Footer />
    </div>
  );
}

export default function NewArrivalsPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-[#fcfcfc]">
          <Header />
          <main className="container mx-auto px-4 py-20">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
              {[...Array(8)].map((_, i) => (
                <ProductCardSkeleton key={i} />
              ))}
            </div>
          </main>
        </div>
      }
    >
      <NewArrivalsContent />
    </Suspense>
  );
}
