import React, { useState } from 'react';
import {
  Grid,
  Search,
  ArrowRight,
  Store,
  Sparkles,
  ChevronRight,
  Home,
  Tag,
  Package,
  CheckCircle2,
  Filter,
} from 'lucide-react';
import { WCCategory, WCProduct, getCategoryImageUrl } from '../services/woocommerce';
import { MOCK_WC_CATEGORIES } from '../data/mockWooCommerceData';
import { ProductCard } from './ProductCard';

interface CategoriesPageProps {
  categories?: WCCategory[];
  products?: WCProduct[];
  onSelectCategory: (categorySlug: string) => void;
  onSelectProduct: (product: WCProduct) => void;
  onAddToCart: (product: WCProduct) => void;
  onNavigateHome: () => void;
  onNavigateShop: () => void;
}

export const CategoriesPage: React.FC<CategoriesPageProps> = ({
  categories = MOCK_WC_CATEGORIES,
  products = [],
  onSelectCategory,
  onSelectProduct,
  onAddToCart,
  onNavigateHome,
  onNavigateShop,
}) => {
  const [searchQuery, setSearchQuery] = useState('');

  const displayCategories = categories && categories.length > 0 ? categories : MOCK_WC_CATEGORIES;

  const filteredCategories = displayCategories.filter((cat) => {
    const q = searchQuery.toLowerCase().trim();
    if (!q) return true;
    return (
      cat.name.toLowerCase().includes(q) ||
      cat.slug.toLowerCase().includes(q) ||
      (cat.description && cat.description.toLowerCase().includes(q))
    );
  });

  return (
    <div className="min-h-screen bg-[#FCF8F5] pb-16">
      
      {/* Breadcrumb Header Bar */}
      <div className="bg-[#1C1814] text-white border-b border-amber-900/30 py-3 px-4 sm:px-6 lg:px-8">
        <div className="max-w-7xl mx-auto flex items-center gap-2 text-xs text-amber-200/80 font-medium">
          <button
            onClick={onNavigateHome}
            className="hover:text-amber-100 flex items-center gap-1 transition-colors cursor-pointer"
          >
            <Home className="w-3.5 h-3.5" />
            <span>Home</span>
          </button>
          <ChevronRight className="w-3.5 h-3.5 opacity-50" />
          <span className="text-amber-400 font-bold">Product Categories</span>
        </div>
      </div>

      {/* Hero Banner Header */}
      <section className="bg-gradient-to-b from-[#1C1814] to-[#2B231D] text-white py-12 px-4 sm:px-6 lg:px-8 relative overflow-hidden">
        <div className="absolute inset-0 opacity-10 bg-[radial-gradient(#C81E3D_1px,transparent_1px)] [background-size:16px_16px]" />
        
        <div className="max-w-7xl mx-auto relative z-10 space-y-6 text-center sm:text-left">
          <div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-[#C81E3D]/20 border border-[#C81E3D]/40 text-[#FF6B8B] font-bold text-xs uppercase tracking-widest">
            <Grid className="w-3.5 h-3.5" />
            <span>TIME N LIFE CATALOG DEPARTMENTS</span>
          </div>

          <div className="flex flex-col md:flex-row md:items-end justify-between gap-6">
            <div className="space-y-2 max-w-2xl">
              <h1 className="text-3xl sm:text-4xl md:text-5xl font-playfair font-bold text-amber-50">
                Explore All Product Categories
              </h1>
              <p className="text-sm sm:text-base text-amber-200/80 leading-relaxed font-sans">
                Browse our wide selection of women’s lawn suits, luxury apparel, health & beauty products, home appliances, electronics, jewelry, and lifestyle accessories across Pakistan.
              </p>
            </div>

            {/* Quick Search in Categories */}
            <div className="w-full md:w-80 relative">
              <Search className="w-4 h-4 text-amber-300 absolute left-3.5 top-3.5" />
              <input
                type="text"
                placeholder="Search categories..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-2.5 bg-white/10 backdrop-blur-md border border-amber-500/30 rounded-xl text-xs text-white placeholder-amber-200/60 focus:outline-none focus:ring-2 focus:ring-[#C81E3D]"
              />
            </div>
          </div>
        </div>
      </section>

      {/* Categories Grid Section */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 -mt-6 relative z-20 space-y-12">
        
        {/* Category Cards */}
        {filteredCategories.length === 0 ? (
          <div className="bg-white p-12 text-center rounded-3xl border border-[#F2E5D9] shadow-sm space-y-3">
            <Package className="w-12 h-12 text-slate-300 mx-auto" />
            <h3 className="text-lg font-bold text-slate-800">No categories found matching "{searchQuery}"</h3>
            <p className="text-xs text-slate-500">Try searching with a different term like Apparel, Beauty, or Home.</p>
            <button
              onClick={() => setSearchQuery('')}
              className="mt-2 inline-flex items-center gap-1.5 px-4 py-2 bg-[#C81E3D] text-white text-xs font-bold rounded-xl"
            >
              Reset Search
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredCategories.map((category) => {
              const bgImg = getCategoryImageUrl(category);

              return (
                <div
                  key={category.id || category.slug}
                  onClick={() => onSelectCategory(category.slug)}
                  className="group bg-white rounded-3xl border border-[#F2E5D9] shadow-sm hover:shadow-xl transition-all duration-300 overflow-hidden flex flex-col justify-between cursor-pointer hover:-translate-y-1"
                >
                  {/* Category Image Header */}
                  <div className="relative h-48 sm:h-52 overflow-hidden bg-slate-900">
                    <img
                      src={bgImg}
                      alt={category.name}
                      onError={(e) => {
                        e.currentTarget.onerror = null;
                        e.currentTarget.src = 'https://images.unsplash.com/photo-1472851294608-062f824d29cc?auto=format&fit=crop&w=800&q=80';
                      }}
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500 opacity-90 group-hover:opacity-100"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />
                    
                    {/* Item Count Badge */}
                    <div className="absolute top-3 right-3 bg-black/60 backdrop-blur-md text-amber-300 border border-amber-400/30 text-[11px] font-extrabold px-3 py-1 rounded-full flex items-center gap-1.5">
                      <Tag className="w-3 h-3 text-[#FF6B8B]" />
                      <span>{category.count ? `${category.count.toLocaleString()} Products` : 'In Stock'}</span>
                    </div>

                    {/* Category Title Overlay */}
                    <div className="absolute bottom-4 left-4 right-4">
                      <h3 className="text-xl sm:text-2xl font-bold font-playfair text-white drop-shadow-md group-hover:text-amber-200 transition-colors">
                        {category.name}
                      </h3>
                    </div>
                  </div>

                  {/* Category Body & Action */}
                  <div className="p-5 flex-1 flex flex-col justify-between space-y-4">
                    <p className="text-xs text-slate-600 line-clamp-2 leading-relaxed">
                      {category.description ||
                        `Explore premium quality ${category.name.toLowerCase()} collection with fast nationwide delivery in Pakistan.`}
                    </p>

                    <div className="pt-2 border-t border-[#F2E5D9] flex items-center justify-between">
                      <span className="text-xs font-bold text-[#C81E3D] group-hover:underline flex items-center gap-1">
                        View Products
                      </span>
                      <div className="w-8 h-8 rounded-full bg-[#FAF5F0] group-hover:bg-[#C81E3D] text-slate-700 group-hover:text-white transition-colors flex items-center justify-center">
                        <ArrowRight className="w-4 h-4" />
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* Catalog Showcase Banner */}
        <div className="bg-gradient-to-r from-[#1C1814] via-[#2B231D] to-[#1C1814] text-white rounded-3xl p-6 sm:p-10 border border-amber-900/40 shadow-xl flex flex-col md:flex-row items-center justify-between gap-6">
          <div className="space-y-2 text-center md:text-left">
            <span className="text-xs font-extrabold text-[#FF6B8B] uppercase tracking-widest flex items-center justify-center md:justify-start gap-1.5">
              <Sparkles className="w-4 h-4" />
              <span>CASH ON DELIVERY NATIONWIDE</span>
            </span>
            <h2 className="text-2xl sm:text-3xl font-playfair font-bold text-amber-100">
              Can’t find what you’re looking for?
            </h2>
            <p className="text-xs sm:text-sm text-amber-200/80 max-w-xl">
              Search our entire multi-vendor inventory or chat with our WhatsApp support team for direct stock assistance.
            </p>
          </div>

          <button
            onClick={onNavigateShop}
            className="px-6 py-3.5 bg-[#C81E3D] hover:bg-[#A6142E] text-white font-bold text-xs uppercase tracking-wider rounded-2xl shadow-lg transition-all flex items-center gap-2 cursor-pointer shrink-0"
          >
            <Store className="w-4 h-4" />
            <span>Open Shop Catalog</span>
            <ArrowRight className="w-4 h-4" />
          </button>
        </div>

        {/* Featured Products Section */}
        {products && products.length > 0 && (
          <div className="space-y-6 pt-4">
            <div className="flex items-center justify-between border-b border-[#F2E5D9] pb-4">
              <div>
                <span className="text-xs font-bold text-[#C81E3D] uppercase tracking-wider">Top Collection</span>
                <h2 className="text-xl sm:text-2xl font-bold font-playfair text-slate-900">Featured Items</h2>
              </div>
              <button
                onClick={onNavigateShop}
                className="text-xs font-bold text-[#C81E3D] hover:underline flex items-center gap-1"
              >
                <span>View All ({products.length})</span>
                <ArrowRight className="w-3.5 h-3.5" />
              </button>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
              {products.slice(0, 10).map((prod) => (
                <ProductCard
                  key={prod.id}
                  product={prod}
                  onSelectProduct={onSelectProduct}
                  onAddToCart={(p, e) => {
                    if (e) e.stopPropagation();
                    onAddToCart(p);
                  }}
                />
              ))}
            </div>
          </div>
        )}

      </section>
    </div>
  );
};
