"use client";

import { useState, useEffect } from "react";
import { api } from "@/lib/api";
import { Product, Category } from "@/types";
import ProductCard from "@/components/product/ProductCard";
import { motion, AnimatePresence } from "framer-motion";
import { Skeleton } from "@/components/ui/Skeleton";
import ProductCardSkeleton from "@/components/product/ProductCardSkeleton";
import Header from "@/components/layout/Header";
import Footer from "@/components/layout/Footer";
import { Search, ChevronRight, 
  LayoutGrid, 
  List, 
  Star, 
  ArrowRight,
  Filter,
  TrendingUp,
  Zap
} from "lucide-react";
import { useSearchParams } from "next/navigation";
import { Suspense } from "react";
import { useTranslation } from "@/lib/i18n";

function ProductsContent() {
  const searchParams = useSearchParams();
  const categoryIdFromQuery = searchParams.get("category_id");
  const isFeaturedFromQuery = searchParams.get("is_featured") === "1";
  const isPopularFromQuery = searchParams.get("is_popular") === "1";
  const searchQueryFromQuery = searchParams.get("search") || "";

  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string | number>(categoryIdFromQuery || "all");
  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(searchQueryFromQuery);
  const { t } = useTranslation();

  useEffect(() => {
    if (categoryIdFromQuery) {
      setSelectedCategory(categoryIdFromQuery);
      setPage(1);
      setProducts([]);
    }
  }, [categoryIdFromQuery]);

  useEffect(() => {
    if (searchQueryFromQuery !== undefined) {
      setSearchQuery(searchQueryFromQuery);
      setPage(1);
      setProducts([]);
    }
  }, [searchQueryFromQuery]);

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await api.getCategories();
        if (response.data) setCategories(response.data);
      } catch (error) {
        console.error("Failed to fetch categories:", error);
      }
    };
    fetchCategories();
  }, []);

  useEffect(() => {
    const fetchProducts = async () => {
      try {
        setLoading(true);
        const params: any = { page };
        if (selectedCategory !== "all") {
          params.category_id = selectedCategory;
        }
        if (isFeaturedFromQuery) {
          params.is_featured = true;
        }
        if (isPopularFromQuery) {
          params.is_popular = 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]);
          }
          // The API might return pagination data in different formats
          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 products:", error);
      } finally {
        setLoading(false);
      }
    };

    const timer = setTimeout(() => {
      fetchProducts();
    }, 300); // Reduced debounce for snappier search

    return () => clearTimeout(timer);
  }, [page, selectedCategory, searchQuery, isFeaturedFromQuery, isPopularFromQuery]);

  const handleCategoryChange = (categoryId: string | number) => {
    setSelectedCategory(categoryId);
    setPage(1);
    setProducts([]);
  };

  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 />
      
      {/* Clean Hero Header */}
      <section className="bg-white border-b border-zinc-100 py-8 md:py-12 relative overflow-hidden">
        <div className="container mx-auto px-4 relative z-10">
          <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6">
            <div className="space-y-2 max-w-2xl">
              <motion.h1 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="text-3xl md:text-5xl font-black text-zinc-900 tracking-tight"
              >
                {selectedCategory === "all" ? t("exploreOur") : categories.find(c => c.id == selectedCategory)?.name || "Premium"}{" "}
                <span className="text-[#2b9d10]">{t("collection")}</span>
              </motion.h1>
              
              <motion.p 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1 }}
                className="text-zinc-500 text-sm md:text-base font-medium leading-relaxed"
              >
                {t("finestQuality")}
              </motion.p>
            </div>
            
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 0.2 }}
              className="flex items-center gap-1 bg-zinc-50 p-1 rounded-xl border border-zinc-100 self-start lg:self-center"
            >
              <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} /> {t("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} /> {t("list")}
              </button>
            </motion.div>
          </div>
        </div>
      </section>

      <main className="container mx-auto px-4 py-8 md:py-12">
        <div className="flex flex-col lg:flex-row gap-8 lg:gap-12">
          {/* Enhanced Sidebar Filters */}
          <aside className="w-full lg:w-72 space-y-8">
            <div className="sticky top-24 space-y-6">
              {/* Simplified Category Filter */}
              <div className="bg-white p-5 rounded-2xl border border-zinc-100 shadow-sm">
                <h3 className="text-[10px] font-black text-zinc-400 uppercase tracking-[0.3em] mb-5 flex items-center gap-2">
                  <Filter size={12} className="text-[#2b9d10]" />
                  Categories
                </h3>
                
                <div className="flex lg:flex-col gap-1.5 overflow-x-auto pb-4 lg:pb-0 no-scrollbar">
                  <button
                    onClick={() => handleCategoryChange("all")}
                    className={`whitespace-nowrap lg:w-full text-left px-4 py-3 rounded-xl text-[10px] font-bold uppercase tracking-wider transition-all flex items-center justify-between shrink-0 ${
                      selectedCategory === "all" 
                        ? "bg-[#2b9d10] text-white" 
                        : "text-zinc-500 hover:bg-zinc-50 hover:text-zinc-900"
                    }`}
                  >
                    All Products
                    <ChevronRight size={12} className={selectedCategory === "all" ? "opacity-100" : "opacity-0"} />
                  </button>
                  
                  {categories.map((category) => (
                    <button
                      key={category.id}
                      onClick={() => handleCategoryChange(category.id)}
                      className={`whitespace-nowrap lg:w-full text-left px-4 py-3 rounded-xl text-[10px] font-bold uppercase tracking-wider transition-all flex items-center justify-between shrink-0 ${
                        selectedCategory == category.id 
                          ? "bg-[#2b9d10] text-white" 
                          : "text-zinc-500 hover:bg-zinc-50 hover:text-zinc-900"
                      }`}
                    >
                      {category.name}
                      <ChevronRight size={12} className={selectedCategory == category.id ? "opacity-100" : "opacity-0"} />
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </aside>

          {/* Product Grid Area */}
          <div className="flex-1">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
              <div className="flex-1 relative">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400" size={16} />
                <input 
                  type="text" 
                  value={searchQuery}
                  onChange={handleSearchChange}
                  placeholder={t("searchProducts")}
                  className="w-full pl-10 pr-4 py-3 bg-white border border-zinc-100 rounded-xl focus:outline-none focus:border-[#2b9d10] transition-all text-sm"
                />
              </div>
              
              <div className="flex items-baseline gap-2">
                <h2 className="text-lg font-bold text-zinc-900">
                  {selectedCategory === "all" ? "All Products" : categories.find(c => c.id == selectedCategory)?.name}
                </h2>
                <span className="text-[10px] font-bold text-[#2b9d10] uppercase tracking-wider">
                  ({products.length})
                </span>
              </div>
            </div>

            {loading && page === 1 ? (
              <div className="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-8">
                {[...Array(9)].map((_, i) => (
                  <ProductCardSkeleton key={i} />
                ))}
              </div>
            ) : products.length > 0 ? (
              <>
                <div className={viewType === 'grid' 
                  ? "grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-8" 
                  : "flex flex-col gap-6 md:gap-8"
                }>
                  <AnimatePresence mode="popLayout">
                    {products.map((product, index) => (
                      <motion.div
                        key={product.id}
                        layout
                        initial={{ opacity: 0, y: 30 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, scale: 0.95 }}
                        transition={{ duration: 0.5, delay: index * 0.05 }}
                      >
                        <ProductCard product={product} />
                      </motion.div>
                    ))}
                  </AnimatePresence>
                </div>

                {hasMore && (
                  <div className="mt-12 text-center">
                    <button
                      onClick={loadMore}
                      disabled={loading}
                      className="bg-white border border-zinc-200 text-zinc-900 px-8 py-3 rounded-xl font-bold text-[11px] uppercase tracking-wider hover:bg-zinc-50 transition-all disabled:opacity-50 inline-flex items-center gap-2"
                    >
                      {loading ? (
                        <div className="w-4 h-4 border-2 border-zinc-200 border-t-zinc-900 rounded-full animate-spin" />
                      ) : (
                        <>{t("loadMoreProducts")} <ArrowRight size={14} /></>
                      )}
                    </button>
                  </div>
                )}
              </>
            ) : (
              <motion.div 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="text-center py-20 bg-white rounded-2xl border border-zinc-100 px-8"
              >
                <div className="w-16 h-16 bg-zinc-50 rounded-xl flex items-center justify-center mx-auto mb-4">
                  <Search size={24} className="text-zinc-300" />
                </div>
                <h2 className="text-xl font-bold text-zinc-900 mb-2">{t("noProductsFound")}</h2>
                <p className="text-zinc-400 text-sm mb-6">{t("noProductsFoundDesc")}</p>
                <button 
                  onClick={() => handleCategoryChange("all")}
                  className="bg-[#2b9d10] text-white px-6 py-3 rounded-xl font-bold text-[11px] uppercase tracking-wider hover:bg-zinc-900 transition-all"
                >
                  {t("viewAllProducts")}
                </button>
              </motion.div>
            )}
          </div>
        </div>
      </main>
      
      <Footer />
    </div>
  );
}

export default function ProductsPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-[#fcfcfc]">
        <Header />
        <main className="container mx-auto px-4 py-8 md:py-12">
          <div className="flex flex-col lg:flex-row gap-8 lg:gap-12">
            <aside className="w-full lg:w-80 space-y-8">
              <Skeleton className="h-64 w-full rounded-2xl" />
              <Skeleton className="hidden lg:block h-64 w-full rounded-2xl" />
            </aside>
            <div className="flex-1 space-y-8">
              <Skeleton className="h-14 w-full rounded-2xl" />
              <div className="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-8">
                {[...Array(6)].map((_, i) => (
                  <ProductCardSkeleton key={i} />
                ))}
              </div>
            </div>
          </div>
        </main>
      </div>
    }>
      <ProductsContent />
    </Suspense>
  );
}
