import React, { useState } from 'react';
import { Search, CheckCircle2, DownloadCloud, Box, PackageOpen, Filter, Layers, Check, Package, X, ArrowLeft } from 'lucide-react';
import { 
  useCatalogueProducts, 
  useCatalogueBrands, 
  useImportedCatalogueRefs, 
  useImportCatalogueProduct,
  useTenantCategories
} from '../hooks/useCatalogueImport';
import { CatalogueProduct, ImportCatalogueProductRequest } from '../services/catalogueApi';
import { useStoreCatalogue, usePriceEverywhere } from '../services/storeCatalogue';
import { useFiestaTenantLocations, useFiestaProductLocations } from '../services/fiestaQueries';
import { num as fnum } from '../services/fiestaApi';
import ImportProductModal from './ImportProductModal';

interface CatalogueBrowserProps {
  tenantid: number;
  locationid: number;
  onClose?: () => void;
}

export default function CatalogueBrowser({ tenantid, locationid, onClose }: CatalogueBrowserProps) {
  const [brand, setBrand] = useState<string | undefined>(undefined);
  const [keyword, setKeyword] = useState<string>('');
  const [debouncedKeyword, setDebouncedKeyword] = useState<string>('');
  
  const [importingProduct, setImportingProduct] = useState<CatalogueProduct | null>(null);

  const [isLocalSidebarOpen, setIsLocalSidebarOpen] = useState(false);

  // Debounce search
  React.useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedKeyword(keyword);
    }, 400);
    return () => clearTimeout(handler);
  }, [keyword]);

  const { data: catalogueData, isLoading: isLoadingProducts } = useCatalogueProducts(brand, debouncedKeyword);
  const products = catalogueData?.products ?? [];
  const total = catalogueData?.total ?? 0;

  const { data: brandsData = [], isLoading: isLoadingBrands } = useCatalogueBrands();
  
  const { data: importedRefs = new Set<string>() } = useImportedCatalogueRefs(tenantid, brand);
  const { data: tenantCategories = [] } = useTenantCategories(tenantid);
  const storeCat = useStoreCatalogue(tenantid, locationid);
  
  const importProductMutation = useImportCatalogueProduct(tenantid, locationid);

  // Every outlet the tenant runs — the price entered on import has to reach all
  // of them, not just the one this browser happens to be scoped to.
  const locationsQ = useFiestaTenantLocations(tenantid);
  const allLocationIds = React.useMemo(() => {
    const ids = (locationsQ.data ?? []).map((l) => fnum(l.locationid)).filter((id) => id > 0);
    return ids.length ? ids : [locationid];
  }, [locationsQ.data, locationid]);

  const { priceEverywhere } = usePriceEverywhere(tenantid);
  // Used only to look the freshly-created tenant productid back up: the import
  // response returns just {status, message}, and the price has to be attached to
  // the tenant's own productid, not the global catalogueid.
  const importedRowsQ = useFiestaProductLocations({ tenantid, locationid, pagesize: 500 });

  const handleImportSubmit = (item: ImportCatalogueProductRequest) => {
    importProductMutation.mutate([item], {
      onSuccess: async () => {
        setImportingProduct(null);
        if (!(item.retailprice > 0)) return;
        // The import writes the price to products.retailprice, but the per-store
        // price on productlocations is what the staff catalogue, the customer
        // app and the order all read — so publish it across the tenant here.
        // Status stays 'Draft' to match what the import itself wrote; this step
        // prices the product, it doesn't change its lifecycle.
        try {
          const { data } = await importedRowsQ.refetch();
          const row = (data ?? []).find((r) => fnum(r.catalogueid) === Number(item.catalogueid));
          const productid = fnum(row?.productid);
          if (productid) {
            priceEverywhere(productid, item.retailprice, allLocationIds, { status: 'Draft' });
          }
        } catch {
          // Import succeeded; only the price broadcast failed. The admin can
          // still set it from the Admin Catalogue, so don't fail the import.
        }
      },
      onError: (err: any) => {
        alert(err.message || 'Failed to import product.');
      }
    });
  };

  return (
    <div className="flex flex-col h-full bg-transparent relative animate-in fade-in duration-300 font-sans text-slate-700">
      
      <div className="flex flex-col xl:flex-row gap-6 mt-2 flex-1 min-h-0 overflow-hidden pb-4">
        {/* Left Side: Filters */}
        {isLocalSidebarOpen && (
          <div className="w-full xl:w-52 shrink-0 flex flex-col gap-5 pr-2 pb-2">
            <div className="bg-white border border-slate-200 shadow-sm overflow-hidden flex-1 min-h-0 flex flex-col rounded-none">
              <div className="p-4 bg-slate-50 border-b border-slate-100 shrink-0">
                <h3 className="font-bold text-sm text-slate-800 flex items-center gap-2">
                  <Filter size={16} className="text-[#662582]" /> Filter Brands
                </h3>
              </div>
            <div className="p-4 space-y-5 overflow-y-auto custom-scrollbar">
              <div>
                <h3 className="text-[11px] font-extrabold text-slate-400 uppercase tracking-widest mb-3 flex items-center gap-1.5">
                  <Layers size={14} className="text-[#662582]" /> Brands
                </h3>
                {isLoadingBrands ? (
                  <span className="text-xs text-slate-400 py-1.5">Loading brands...</span>
                ) : (
                  <div className="space-y-1.5">
                    {brandsData.map((b) => (
                      <label key={b.brand} className="flex items-center gap-3 p-2 rounded-none hover:bg-slate-50 cursor-pointer group transition-colors">
                        <div className="relative flex items-center justify-center shrink-0">
                          <input
                            type="checkbox"
                            checked={brand === b.brand}
                            onChange={() => setBrand(brand === b.brand ? undefined : b.brand)}
                            className="peer appearance-none w-5 h-5 border-2 border-slate-300 rounded-none checked:border-[#662582] checked:bg-[#662582] transition-colors cursor-pointer"
                          />
                          <Check size={12} className="absolute text-white opacity-0 peer-checked:opacity-100 pointer-events-none" strokeWidth={3} />
                        </div>
                        <span className={`text-xs font-semibold select-none transition-colors truncate ${brand === b.brand ? 'text-[#662582]' : 'text-slate-600 group-hover:text-slate-900'}`}>
                          {b.brand.replace('brand_', '').toUpperCase()}
                        </span>
                        <span className="ml-auto text-[10px] text-slate-400 font-bold">{b.product_count}</span>
                      </label>
                    ))}
                  </div>
                )}
              </div>

              {(brand || keyword) && (
                <button 
                  onClick={() => { setBrand(undefined); setKeyword(''); }}
                  className="w-full py-2 bg-slate-100 text-slate-600 rounded-none text-[10px] font-bold uppercase tracking-wider hover:bg-slate-200 transition-colors cursor-pointer border-none mt-4"
                >
                  Clear All Filters
                </button>
              )}
            </div>
          </div>
        </div>
        )}

        {/* Right Side: Main Content Area */}
        <div className="flex-1 min-w-0 overflow-y-auto custom-scrollbar bg-white/40 backdrop-blur-md border border-[#e2e8f0] p-5 shadow-sm flex flex-col rounded-none">
          <div className={`flex justify-between gap-4 mb-5 shrink-0 ${isLocalSidebarOpen ? 'flex-col lg:flex-row lg:items-center items-start' : 'flex-col lg:flex-row lg:items-center items-start'}`}>
            <div className="flex-1 min-w-0 pr-4 flex items-start gap-2">
              {onClose && (
                <button
                  onClick={onClose}
                  className="p-1.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-100 hover:text-[#662582] transition-colors mt-0.5 cursor-pointer shrink-0"
                  title="Back to Products"
                >
                  <ArrowLeft size={16} />
                </button>
              )}
              <button
                onClick={() => setIsLocalSidebarOpen(!isLocalSidebarOpen)}
                className="p-1.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-100 hover:text-[#662582] transition-colors mt-0.5 cursor-pointer shrink-0"
                title="Toggle Filters"
              >
                <Filter size={16} />
              </button>
              <div>
                <h3 className="font-sans font-bold text-sm text-[#0f172a] flex items-center gap-1.5 flex-wrap">
                  <Box size={15} className="text-[#662582] shrink-0" /> <span className="truncate">Global Product Catalogue</span>
                  <div className="flex items-center gap-1.5 ml-1">
                    <span className="text-[9px] text-[#662582] font-bold bg-purple-50 px-1.5 py-0.5 rounded-none border border-purple-100/50 whitespace-nowrap">
                      {total} product{total === 1 ? '' : 's'} available
                    </span>
                  </div>
                </h3>
                <p className="text-[9px] text-zinc-400 font-medium mt-1 truncate">Browse global FMCG products and import them into your local merchant catalogue.</p>
              </div>
            </div>

            <div className="flex flex-nowrap items-center gap-2 shrink-0">
              <div className="relative bg-slate-50 border border-slate-200 rounded-none flex items-center h-[32px] px-2.5 shadow-sm min-w-[200px] hover:border-purple-300 transition-colors group focus-within:border-purple-500 focus-within:bg-white focus-within:ring-2 focus-within:ring-purple-100">
                <Search size={14} className="text-slate-400 group-focus-within:text-purple-600 transition-colors shrink-0" />
                <input 
                  type="text"
                  placeholder="Search catalogue..."
                  value={keyword}
                  onChange={(e) => setKeyword(e.target.value)}
                  className="bg-transparent border-none outline-none text-xs font-semibold text-slate-700 ml-2 w-full placeholder:text-slate-400 placeholder:font-medium"
                />
                {keyword && (
                  <button 
                    onClick={() => setKeyword('')} 
                    className="ml-1 text-slate-400 hover:text-slate-700 bg-slate-200 hover:bg-slate-300 rounded-full p-0.5 transition-colors"
                  >
                    <X size={10} />
                  </button>
                )}
              </div>
            </div>
          </div>

          {isLoadingProducts ? (
            <div className="flex flex-col items-center justify-center flex-1 text-slate-400 gap-3">
              <div className="w-6 h-6 border-2 border-purple-650 border-t-transparent rounded-full animate-spin"></div>
              <span className="text-xs font-bold uppercase tracking-widest">Loading catalogue...</span>
            </div>
          ) : products.length === 0 ? (
            <div className="text-center py-xl text-zinc-400 text-xs font-bold flex-1 flex items-center justify-center">
              No products match your selection.
            </div>
          ) : (
            <div className="flex-1 min-w-0">
              <div className={`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 ${!isLocalSidebarOpen ? 'xl:grid-cols-5 2xl:grid-cols-6' : 'xl:grid-cols-4 2xl:grid-cols-5'} gap-4`}>
                {products.map(p => {
                  const isImported = storeCat.has(String(p.id));
                  
                  return (
                    <div 
                      key={`${p.brand}:${p.id}`} 
                      onClick={() => setImportingProduct(p)}
                      className="bg-white/80 backdrop-blur-md border border-[#e2e8f0] rounded-none flex flex-col shadow-sm hover:shadow-[0_12px_24px_rgba(99,102,241,0.06)] hover:border-[#662582]/40 hover:-translate-y-1 transition-all duration-300 relative group overflow-hidden cursor-pointer"
                    >
                      <div className="w-full h-48 bg-white p-4 relative overflow-hidden shrink-0 border-b border-slate-100 flex items-center justify-center">
                        {p.images && p.images.length > 0 ? (
                          <img 
                            src={p.images[0]} 
                            alt={p.product_name} 
                            className="w-full h-full object-contain mix-blend-multiply group-hover:scale-110 transition-transform duration-700 ease-in-out" 
                          />
                        ) : (
                          <Box className="w-16 h-16 text-slate-200" />
                        )}
                        <div className="absolute inset-0 bg-gradient-to-t from-slate-900/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none" />
                      </div>
                      
                      <div className="p-3 flex flex-col flex-1 gap-2">
                        <div className="flex-1 min-w-0 pb-2">
                          <h4 className="font-bold text-[#0f172a] text-xs leading-snug group-hover:text-[#662582] transition-colors line-clamp-2" title={p.product_name}>
                            {p.product_name}
                          </h4>
                          <p className="text-[10px] text-zinc-500 font-bold font-mono tracking-tight mt-1">ID: {p.id}</p>
                        </div>
                        
                        <div className="mt-auto pt-2 border-t border-slate-100/50 flex flex-col gap-2">
                          <div className="flex items-center justify-between">
                            <span className="text-[10px] text-slate-500 font-medium">{p.size || 'N/A'}</span>
                            <span className="text-[11px] font-extrabold font-mono text-slate-800">{p.price_range || 'N/A'}</span>
                          </div>
                          
                          {isImported ? (
                            <button 
                              onClick={(e) => { e.stopPropagation(); setImportingProduct(p); }}
                              className="w-full bg-emerald-50 text-emerald-700 border border-emerald-200 px-3 py-2 rounded-none text-[10px] font-bold uppercase tracking-wider transition-all shadow-sm flex items-center justify-center gap-1.5 cursor-pointer"
                            >
                              <CheckCircle2 size={12} />
                              Imported
                            </button>
                          ) : (
                            <button 
                              onClick={(e) => { 
                                e.stopPropagation(); 
                                const validCategory = tenantCategories.find(c => c.categoryid > 0)?.categoryid || (tenantCategories[0]?.categoryid ?? 2);
                                handleImportSubmit({
                                  tenantid,
                                  locationid,
                                  brand: p.brand,
                                  catalogueid: p.id,
                                  categoryid: validCategory,
                                  subcategoryid: 0,
                                  quantity: 0,
                                  stocktype: "in",
                                  // Draft: lands in the Admin Catalogue only. It only becomes
                                  // visible to store users once the admin explicitly publishes
                                  // it via "Add to Store Catalogue" (InventoryView).
                                  status: "Draft",
                                  retailprice: 0,
                                  productcost: 0,
                                  taxpercent: 0,
                                });
                              }}
                              className="w-full bg-[#f8fafc] hover:bg-[#662582] text-slate-600 hover:text-white border border-slate-200 hover:border-[#662582] px-3 py-2 rounded-none text-[10px] font-bold uppercase tracking-wider transition-all shadow-sm flex items-center justify-center gap-1.5 cursor-pointer"
                            >
                              <DownloadCloud size={12} />
                              Import Product
                            </button>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>

      {importingProduct && (
        <ImportProductModal 
          product={importingProduct}
          tenantid={tenantid}
          locationid={locationid}
          onClose={() => setImportingProduct(null)}
          onImport={handleImportSubmit}
          isImported={storeCat.has(String(importingProduct.id))}
        />
      )}
      
      {importProductMutation.isPending && (
        <div className="absolute inset-0 bg-white/50 backdrop-blur-sm z-50 flex flex-col items-center justify-center gap-3">
          <div className="w-8 h-8 border-4 border-purple-650 border-t-transparent rounded-full animate-spin"></div>
          <div className="text-sm font-bold uppercase tracking-widest text-slate-700 shadow-sm bg-white px-4 py-2 rounded-none border border-slate-200">Importing product...</div>
        </div>
      )}
    </div>
  );
}
