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');

  // 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,
  );

  // A price is mandatory. Importing at ₹0 is what left every catalogue product
  // on the platform priced at nothing: the staff catalogue showed "—", the
  // customer app charged nothing, and each order booked orderamount 0.
  const priceValue = Number(retailPrice);
  const canImport = Boolean(categoryId) && priceValue > 0;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!canImport) return;

    onImport({
      tenantid,
      locationid,
      brand: product.brand,
      catalogueid: product.id,
      categoryid: Number(categoryId),
      subcategoryid: subcategoryId ? Number(subcategoryId) : 0,
      // Importing lists the product; it does not deliver stock. Quantity lands
      // via the request → approve → Mark as Received flow.
      quantity: 0,
      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: priceValue,
      productcost: Number(productCost) || 0,
      taxpercent: Number(taxPercent) || 0,
    });
  };

  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>
          ) : (
            <form onSubmit={handleSubmit} 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">
                The global catalogue only carries an indicative price range, so set your own
                selling price here. It applies to every store under your tenant.
              </p>

              <div className="grid grid-cols-2 gap-3">
                <label className="flex flex-col gap-1.5 col-span-2">
                  <span className="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">
                    Selling Price (₹) <span className="text-rose-500">*</span>
                  </span>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 font-bold pointer-events-none">₹</span>
                    <input
                      type="number"
                      min="0"
                      step="0.01"
                      value={retailPrice}
                      onChange={(e) => setRetailPrice(e.target.value)}
                      placeholder="e.g. 50"
                      className="w-full pl-7 pr-3 py-2.5 border border-slate-200 rounded-xl text-sm font-bold text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-[#662582]/20 focus:border-[#662582] transition-all"
                    />
                  </div>
                </label>

                <label className="flex flex-col gap-1.5">
                  <span className="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Cost (₹)</span>
                  <input
                    type="number"
                    min="0"
                    step="0.01"
                    value={productCost}
                    onChange={(e) => setProductCost(e.target.value)}
                    placeholder="0"
                    className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-sm font-bold text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-[#662582]/20 focus:border-[#662582] transition-all"
                  />
                </label>

                <label className="flex flex-col gap-1.5">
                  <span className="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Tax (%)</span>
                  <input
                    type="number"
                    min="0"
                    step="0.01"
                    value={taxPercent}
                    onChange={(e) => setTaxPercent(e.target.value)}
                    className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-sm font-bold text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-[#662582]/20 focus:border-[#662582] transition-all"
                  />
                </label>

                <label className="flex flex-col gap-1.5">
                  <span className="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">
                    Category <span className="text-rose-500">*</span>
                  </span>
                  <select
                    value={categoryId}
                    onChange={(e) => { setCategoryId(e.target.value); setSubcategoryId(''); }}
                    disabled={isLoadingCategories}
                    className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-xs font-bold text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-[#662582]/20 focus:border-[#662582] transition-all disabled:opacity-60"
                  >
                    <option value="">{isLoadingCategories ? 'Loading…' : 'Select…'}</option>
                    {categories.map((c) => (
                      <option key={c.categoryid} value={c.categoryid}>{c.categoryname}</option>
                    ))}
                  </select>
                </label>

                <label className="flex flex-col gap-1.5">
                  <span className="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Subcategory</span>
                  <select
                    value={subcategoryId}
                    onChange={(e) => setSubcategoryId(e.target.value)}
                    disabled={!categoryId || isLoadingSubcats}
                    className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-xs font-bold text-slate-900 bg-white focus:outline-none focus:ring-2 focus:ring-[#662582]/20 focus:border-[#662582] transition-all disabled:opacity-60"
                  >
                    <option value="">{!categoryId ? 'Pick a category first' : isLoadingSubcats ? 'Loading…' : 'None'}</option>
                    {subcategories.map((s: any) => (
                      <option key={s.subcategoryid} value={s.subcategoryid}>{s.subcategoryname}</option>
                    ))}
                  </select>
                </label>
              </div>

              <button
                type="submit"
                disabled={!canImport}
                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 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
              >
                <Plus size={18} strokeWidth={2.5} />
                Import Product
              </button>
              {!canImport && (
                <p className="text-[10px] font-semibold text-slate-500 text-center flex items-center justify-center gap-1">
                  <AlertCircle size={11} className="text-amber-500" />
                  A selling price and category are required.
                </p>
              )}
            </form>
          )}
        </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>
  );
}
