import React, { useState } from 'react';
import { X, Save, AlertCircle, CheckCircle, DownloadCloud, Plus, Box } from 'lucide-react';
import { CatalogueProduct, ImportCatalogueProductRequest } from '../services/catalogueApi';
import { useProductSubcategories, useTenantCategories } from '../hooks/useCatalogueImport';
import { SlideDrawer } from './consoleUi';
import FMCGHoverOverlay from './FMCGHoverOverlay';

interface ImportProductModalProps {
  product: CatalogueProduct;
  tenantid: number;
  locationid: number;
  onClose: () => void;
  onImport: (item: ImportCatalogueProductRequest) => void;
  isImported?: boolean;
}

export default function ImportProductModal({
  product,
  tenantid,
  locationid,
  onClose,
  onImport,
  isImported = false
}: ImportProductModalProps) {
  const [categoryId, setCategoryId] = useState<string>('');
  const [subcategoryId, setSubcategoryId] = useState<string>('');
  const [retailPrice, setRetailPrice] = useState<string>('');
  const [productCost, setProductCost] = useState<string>('');
  const [taxPercent, setTaxPercent] = useState<string>('0');
  const [quantity, setQuantity] = useState<string>('1');

  // Categories this tenant's own products actually use
  const { data: categories = [], isLoading: isLoadingCategories } = useTenantCategories(tenantid);

  // Subcategories scoped to selected category
  const { data: subcategories = [], isLoading: isLoadingSubcats } = useProductSubcategories(
    tenantid,
    categoryId ? Number(categoryId) : undefined,
  );

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!categoryId || !retailPrice || !productCost) {
      alert("Please fill in all required fields.");
      return;
    }

    onImport({
      tenantid,
      locationid,
      brand: product.brand,
      catalogueid: product.id,
      categoryid: Number(categoryId),
      subcategoryid: subcategoryId ? Number(subcategoryId) : 0,
      quantity: Number(quantity),
      stocktype: "in",
      // Draft: lands in the Admin Catalogue only, published to the store
      // catalogue separately via the explicit "Add to Store Catalogue" step.
      status: "Draft",
      retailprice: Number(retailPrice),
      productcost: Number(productCost),
      taxpercent: Number(taxPercent),
    });
  };

  return (
    <SlideDrawer
      isOpen={!!product}
      onClose={onClose}
      title="Global Product Details"
    >
      <div className="flex flex-col gap-6 pb-8 text-xs font-sans">
        
        {/* Clean Image Container */}
        <div className="w-full h-64 bg-white rounded-2xl border border-slate-200 overflow-hidden relative flex items-center justify-center p-4 shadow-xs">
          {product.images && product.images.length > 0 ? (
            <img src={product.images[0]} alt={product.product_name} className="w-auto h-full max-w-full object-contain mix-blend-multiply" />
          ) : (
            <Box size={48} className="text-slate-300" />
          )}
          {isImported && (
            <div className="absolute top-3 right-3 flex items-center gap-1 bg-emerald-500 text-white text-[10px] font-extrabold uppercase px-2 py-1 shadow-sm rounded-md">
              <CheckCircle size={12} />
              In Store Catalogue
            </div>
          )}
        </div>

        {/* Title & Basics */}
        <div>
          <p className="text-xs font-bold text-slate-400 font-mono tracking-tight mb-1">ID: {product.id}</p>
          <h3 className="text-xl font-extrabold text-slate-900 leading-tight mb-3">{product.product_name}</h3>
          <div className="flex flex-wrap items-center gap-2">
            <span className="px-2.5 py-1 rounded bg-purple-50 text-[#662582] text-[10px] font-extrabold uppercase tracking-wider border border-purple-100">
              {product.brand.replace('brand_', '')}
            </span>
          </div>
        </div>

        {/* Price Range Container */}
        <div className="bg-slate-50/90 p-4 rounded-xl border border-slate-200 flex items-center justify-between shadow-xs">
          <div>
            <span className="text-[10px] font-extrabold text-slate-400 uppercase tracking-widest block mb-0.5">Price Range</span>
            <div className="text-2xl font-black text-slate-900 font-mono tracking-tight">
              {product.price_range || 'N/A'}
            </div>
          </div>
          {product.size && (
            <span className="px-3 py-1.5 rounded-lg bg-white text-slate-700 text-xs font-extrabold uppercase tracking-wider border border-slate-200 shadow-2xs">
              Size: {product.size}
            </span>
          )}
        </div>

        {/* Import Action Container */}
        <div className="bg-slate-50/80 rounded-2xl border border-slate-200 p-5 space-y-4 shadow-xs">
          {isImported ? (
            <div className="p-4 bg-emerald-50/80 border border-emerald-200 rounded-xl flex items-center gap-3 text-xs text-emerald-800 font-semibold shadow-xs">
              <CheckCircle size={22} className="text-emerald-600 shrink-0" />
              <div>
                <div className="font-extrabold text-sm text-emerald-900">Imported</div>
                <p className="text-[11px] text-emerald-700 font-medium mt-0.5">This product is available in your Admin Catalogue. Set pricing and store parameters in the Admin Catalogue.</p>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              <div className="flex items-center justify-between border-b border-slate-200 pb-3">
                <h4 className="font-extrabold text-slate-800 text-sm flex items-center gap-2">
                  <DownloadCloud size={16} className="text-[#662582]" /> Import Product
                </h4>
                <span className="text-[10px] font-semibold text-slate-500">Global FMCG</span>
              </div>
              <p className="text-[11px] text-slate-600 font-medium leading-relaxed">
                Import this product to your Admin Catalogue. Selling price and outlet parameters will be managed directly in your Admin Catalogue.
              </p>
              <button 
                onClick={() => {
                  const validCategory = categories.find(c => c.categoryid > 0)?.categoryid || (categories[0]?.categoryid ?? 2);
                  onImport({
                    tenantid,
                    locationid,
                    brand: product.brand,
                    catalogueid: product.id,
                    categoryid: validCategory,
                    subcategoryid: 0,
                    quantity: 0,
                    stocktype: "in",
                    status: "Draft",
                    retailprice: 0,
                    productcost: 0,
                    taxpercent: 0,
                  });
                }} 
                className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl text-sm font-extrabold transition-all bg-[#662582] hover:bg-[#531e6a] text-white shadow-md cursor-pointer"
              >
                <Plus size={18} strokeWidth={2.5} />
                Import Product
              </button>
            </div>
          )}
        </div>

        {/* Retail Packaging Details */}
        <div>
          <h4 className="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2">Retail Packaging Info</h4>
          <FMCGHoverOverlay 
            productId={String(product.id)} 
            category={product.brand} 
            productName={product.product_name} 
            product={product} 
          />
        </div>

      </div>
    </SlideDrawer>
  );
}
