import React, { useState, useEffect } from 'react';
import { Search, X, Tag, ArrowRight, Loader2 } from 'lucide-react';
import { WCProduct, getWCProducts, stripHtmlTags } from '../services/woocommerce';

interface SearchModalProps {
  isOpen: boolean;
  onClose: () => void;
  products: WCProduct[];
  onSelectProduct: (product: WCProduct) => void;
  onNavigateShop2: (searchQuery?: string) => void;
}

export const SearchModal: React.FC<SearchModalProps> = ({
  isOpen,
  onClose,
  products: initialFallbackProducts,
  onSelectProduct,
  onNavigateShop2,
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [apiProducts, setApiProducts] = useState<WCProduct[]>([]);
  const [isSearching, setIsSearching] = useState<boolean>(false);

  const popularTags = [
    'Health & Beauty',
    'Trimmers & Clippers',
    'Handbags',
    'Skin Care',
    'Watches',
    'Smartwatches',
    'Shilajit',
    'Moringa',
  ];

  // Debounced API search so homepage/modal search returns the EXACT same results as Shop page
  useEffect(() => {
    const q = searchTerm.trim();
    if (!q) {
      setApiProducts([]);
      setIsSearching(false);
      return;
    }

    setIsSearching(true);
    const timer = setTimeout(async () => {
      try {
        const res = await getWCProducts(undefined, 24, 1, q);
        if (res && res.products) {
          setApiProducts(res.products);
        } else {
          setApiProducts([]);
        }
      } catch {
        setApiProducts([]);
      } finally {
        setIsSearching(false);
      }
    }, 300);

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

  const handleSubmitSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchTerm.trim()) {
      onNavigateShop2(searchTerm.trim());
      onClose();
    }
  };

  if (!isOpen) return null;

  // Use API results if user searched, else fallback to local
  const displayProducts = searchTerm.trim() ? apiProducts : [];

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center pt-16 px-4 bg-black/60 backdrop-blur-xs animate-in fade-in duration-200">
      <div className="bg-[#FFFDFB] w-full max-w-2xl rounded-2xl shadow-2xl border border-[#F2E5D9] overflow-hidden">
        
        {/* Search Header Form */}
        <form onSubmit={handleSubmitSearch} className="p-4 border-b border-[#F2E5D9] flex items-center gap-3">
          {isSearching ? (
            <Loader2 className="w-5 h-5 text-[#C81E3D] animate-spin shrink-0" />
          ) : (
            <Search className="w-5 h-5 text-[#C81E3D] shrink-0" />
          )}
          <input
            type="text"
            placeholder="Search 7,500+ products (e.g., Moringa, Shilajit, Trimmer)..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="flex-1 bg-transparent text-slate-800 text-base focus:outline-none font-sans placeholder:text-slate-400"
            autoFocus
          />
          {searchTerm && (
            <button
              type="submit"
              className="px-3.5 py-1.5 rounded-lg bg-[#C81E3D] text-white text-xs font-bold hover:bg-[#A6142E] transition-colors cursor-pointer shrink-0"
            >
              Search
            </button>
          )}
          <button
            type="button"
            onClick={onClose}
            className="p-1 rounded-full hover:bg-rose-50 text-slate-400 hover:text-slate-700 transition-colors cursor-pointer shrink-0"
          >
            <X className="w-5 h-5" />
          </button>
        </form>

        {/* Live Search Results */}
        {searchTerm.trim() ? (
          <div className="p-4 space-y-2 max-h-80 overflow-y-auto">
            <div className="flex items-center justify-between text-xs font-bold text-slate-500 uppercase tracking-wider px-2">
              <span>Search Results ({displayProducts.length})</span>
              {isSearching && <span className="text-amber-700 font-normal normal-case">Searching catalog...</span>}
            </div>

            {isSearching && displayProducts.length === 0 ? (
              <div className="p-8 text-center text-xs text-slate-500 flex flex-col items-center gap-2">
                <Loader2 className="w-6 h-6 text-[#C81E3D] animate-spin" />
                <span>Searching WooCommerce database...</span>
              </div>
            ) : displayProducts.length > 0 ? (
              displayProducts.map((p) => (
                <div
                  key={p.id}
                  onClick={() => {
                    onSelectProduct(p);
                    onClose();
                  }}
                  className="p-3 rounded-xl bg-[#FAF5F0] hover:bg-rose-50 border border-[#F2E5D9] flex items-center justify-between cursor-pointer transition-colors"
                >
                  <div className="flex items-center gap-3 min-w-0">
                    <img
                      src={p.images?.[0]?.src || 'https://timenlife.shop/wp-content/uploads/2023/logo.png'}
                      alt={p.name}
                      className="w-10 h-10 object-cover rounded-lg border border-[#E8D9CC] shrink-0"
                    />
                    <div className="min-w-0">
                      <h5 className="text-xs font-bold text-slate-800 truncate">{stripHtmlTags(p.name)}</h5>
                      <span className="text-[10px] text-[#B8860B] uppercase block truncate">{stripHtmlTags(p.categories?.[0]?.name || '')}</span>
                    </div>
                  </div>
                  <div className="text-xs font-extrabold text-[#C81E3D] shrink-0 ml-3">
                    Rs {parseFloat(p.sale_price || p.price || '0').toLocaleString('en-PK')}
                  </div>
                </div>
              ))
            ) : (
              <div className="p-6 text-center text-xs text-slate-500">
                No products found matching "{searchTerm}". Try another keyword or browse the catalog.
              </div>
            )}
          </div>
        ) : (
          /* Popular Searches */
          <div className="p-6 space-y-4">
            <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-400">
              <Tag className="w-3.5 h-3.5 text-[#C81E3D]" />
              <span>Popular Category Searches</span>
            </div>
            <div className="flex flex-wrap gap-2">
              {popularTags.map((tag) => (
                <button
                  key={tag}
                  type="button"
                  onClick={() => setSearchTerm(tag)}
                  className="px-3.5 py-1.5 rounded-full text-xs font-medium bg-rose-50 text-[#C81E3D] hover:bg-[#C81E3D] hover:text-white transition-colors border border-rose-100 cursor-pointer"
                >
                  {tag}
                </button>
              ))}
            </div>
          </div>
        )}

        <div className="p-4 bg-[#FAF5F0] border-t border-[#F2E5D9] flex items-center justify-between text-xs text-slate-500">
          <button
            type="button"
            onClick={() => {
              onNavigateShop2(searchTerm.trim() || undefined);
              onClose();
            }}
            className="text-[#C81E3D] font-bold hover:underline flex items-center gap-1 cursor-pointer"
          >
            <span>
              {searchTerm.trim()
                ? `View All Matching Products in Shop Page ("${searchTerm.trim()}")`
                : 'Browse All Products in Shop Catalog'}
            </span>
            <ArrowRight className="w-3.5 h-3.5" />
          </button>
          <span>Press ESC to close</span>
        </div>

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