import React from 'react';
import { createPortal } from 'react-dom';
import { X, CheckCircle2, ArrowRight } from 'lucide-react';
import { useCompare } from '../contexts/CompareContext';

export default function ComparisonModal() {
  const { selectedProducts, isComparing, setIsComparing, removeProduct, clearSelection, hideCompareBar } = useCompare();

  if (selectedProducts.length === 0) return null;

  return createPortal(
    <>
      {/* Sticky Comparison Bar */}
      {!isComparing && !hideCompareBar && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[9999] bg-white border border-slate-200 shadow-[0_12px_40px_rgba(0,0,0,0.12)] rounded-full px-4 py-3 flex items-center gap-4 transition-all duration-300">
          <div className="flex items-center gap-2">
            <span className="bg-[#662582] text-white w-6 h-6 flex items-center justify-center rounded-full font-bold text-xs">
              {selectedProducts.length}
            </span>
            <span className="text-sm font-bold text-slate-800 hidden sm:inline">items selected</span>
          </div>
          
          <div className="flex items-center -space-x-3 pr-4 border-r border-slate-200">
            {selectedProducts.map((p) => (
              <img key={p.id} src={p.image} alt={p.name} className="w-8 h-8 rounded-full border-2 border-white bg-slate-100 object-cover shadow-sm" />
            ))}
          </div>

          <div className="flex items-center gap-3 pl-2">
            <button 
              onClick={clearSelection}
              className="text-xs font-bold text-slate-500 hover:text-slate-800 transition-colors"
            >
              Clear
            </button>
            <button
              onClick={() => setIsComparing(true)}
              className="bg-[#662582] hover:bg-purple-800 text-white px-5 py-2 rounded-full font-bold text-sm shadow-md transition-colors flex items-center gap-2"
            >
              Compare Now <ArrowRight size={14} />
            </button>
          </div>
        </div>
      )}

      {/* Comparison Drawer */}
      {isComparing && (
        <div className="fixed inset-0 bg-[#0f172a]/60 backdrop-blur-md z-[250] flex flex-col justify-end">
          <div className="bg-white border-t border-[#e2e8f0] w-full h-[80vh] sm:h-[70vh] shadow-[0_-20px_50px_rgba(0,0,0,0.15)] rounded-t-3xl overflow-hidden flex flex-col animate-in slide-in-from-bottom duration-300">
            
            {/* Header */}
            <div className="flex items-center justify-between p-5 border-b border-slate-100 bg-slate-50 shrink-0">
              <div className="flex items-center gap-3">
                <h2 className="text-xl font-extrabold text-slate-900 tracking-tight">Product Comparison</h2>
                <span className="bg-[#662582] text-white text-xs font-bold px-2 py-0.5 rounded-full">
                  {selectedProducts.length} items
                </span>
              </div>
              <div className="flex items-center gap-3">
                {selectedProducts.length < 5 && (
                  <button
                    onClick={() => setIsComparing(false)}
                    className="text-xs font-bold text-[#662582] hover:bg-purple-50 bg-white px-3 py-1.5 rounded-lg border border-purple-200 shadow-sm transition-colors flex items-center gap-1.5"
                  >
                    <span className="text-lg leading-none">+</span> Add Product
                  </button>
                )}
                <button
                  onClick={clearSelection}
                  className="text-xs font-bold text-rose-500 hover:text-rose-600 bg-rose-50 px-3 py-1.5 rounded-lg border border-rose-100 transition-colors"
                >
                  Clear All
                </button>
                <button
                  onClick={() => setIsComparing(false)}
                  className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-slate-200 text-slate-500 transition-colors"
                >
                  <X size={20} />
                </button>
              </div>
            </div>

            {/* Comparison Table / Grid */}
            <div className="flex-1 overflow-x-auto overflow-y-auto p-8 bg-[#f8fafc] custom-scrollbar">
              <div className="flex gap-8 min-w-max pb-8">
                {/* Left Column for labels */}
                {(() => {
                  const isGlobalMode = selectedProducts.some(p => p.isGlobal);
                  
                  return (
                    <>
                      <div className="flex flex-col gap-4 w-40 shrink-0 pt-[140px] sticky left-0 bg-[#f8fafc] z-10 shadow-[15px_0_20px_-5px_rgba(248,250,252,1)]">
                        <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">Category</div>
                        <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">SKU</div>
                        
                        {isGlobalMode ? (
                          <>
                            <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">Wholesale Price</div>
                            <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">Retail (MRP)</div>
                            <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">Profit Margin</div>
                            <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">Global Sales</div>
                            <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">Rating</div>
                          </>
                        ) : (
                          <>
                            <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">Price</div>
                            <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">Units Sold</div>
                            <div className="h-12 flex items-center text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-200/60">Status</div>
                          </>
                        )}
                      </div>

                      {/* Product Columns */}
                      {selectedProducts.map((prod) => (
                        <div key={prod.id} className="w-64 shrink-0 flex flex-col gap-4 relative group">
                          
                          {/* Remove button overlay */}
                          <button 
                            onClick={() => removeProduct(prod.id)}
                            className="absolute -top-3 -right-3 w-7 h-7 bg-white border border-slate-200 rounded-full flex items-center justify-center text-slate-400 hover:text-rose-500 hover:border-rose-200 hover:bg-rose-50 shadow-sm z-20 opacity-0 group-hover:opacity-100 transition-all"
                          >
                            <X size={14} />
                          </button>

                          {/* Product Header Card */}
                          <div className="h-[140px] bg-white rounded-3xl border border-[#e2e8f0] shadow-sm p-4 flex flex-col justify-center relative hover:shadow-md transition-shadow">
                            <div className="flex gap-4 items-center">
                              <img src={prod.image} alt={prod.name} className="w-[72px] h-[72px] rounded-2xl object-cover bg-slate-50 shadow-sm border border-slate-100 shrink-0" />
                              <div className="flex-1 min-w-0">
                                <h3 className="font-extrabold text-slate-900 text-sm leading-snug line-clamp-3">{prod.name}</h3>
                              </div>
                            </div>
                          </div>

                          {/* Metrics */}
                          <div className="h-12 flex items-center border-b border-slate-200/60">
                            <span className="font-bold text-slate-700 text-sm">{prod.category || '—'}</span>
                          </div>
                          
                          <div className="h-12 flex items-center border-b border-slate-200/60">
                            <span className="font-mono text-slate-500 text-xs font-bold tracking-tight">{prod.sku || '—'}</span>
                          </div>
                          
                          {isGlobalMode ? (
                            <>
                              <div className="h-12 flex items-center border-b border-slate-200/60">
                                <span className="font-black text-indigo-900 text-base">
                                  {prod.wholesalePrice ? `₹${prod.wholesalePrice.toLocaleString('en-IN')}` : '—'}
                                </span>
                              </div>
                              <div className="h-12 flex items-center border-b border-slate-200/60">
                                <span className="font-black text-slate-900 text-base">
                                  {prod.mrp ? `₹${prod.mrp.toLocaleString('en-IN')}` : '—'}
                                </span>
                              </div>
                              <div className="h-12 flex items-center border-b border-slate-200/60">
                                {prod.profitMargin ? (
                                  <span className="bg-emerald-100 text-emerald-700 font-black font-mono px-2 py-1 rounded-md text-sm border border-emerald-200">
                                    +{prod.profitMargin}%
                                  </span>
                                ) : (
                                  <span className="text-slate-400">—</span>
                                )}
                              </div>
                              <div className="h-12 flex items-center border-b border-slate-200/60">
                                <span className="font-bold text-indigo-600 font-mono text-sm">
                                  {prod.globalSales != null ? prod.globalSales.toLocaleString('en-IN') : '—'}
                                </span>
                              </div>
                              <div className="h-12 flex items-center border-b border-slate-200/60">
                                <span className="font-black text-amber-500 font-mono text-sm">
                                  {prod.rating ? `${prod.rating.toFixed(1)} ★` : '—'}
                                </span>
                              </div>
                            </>
                          ) : (
                            <>
                              <div className="h-12 flex items-center border-b border-slate-200/60">
                                <span className="font-black text-slate-900 text-base">
                                  {prod.price > 0 ? `₹${prod.price.toLocaleString('en-IN')}` : '—'}
                                </span>
                              </div>
                              <div className="h-12 flex items-center border-b border-slate-200/60">
                                <span className="font-bold text-[#662582] font-mono text-sm">
                                  {prod.unitsSold != null ? prod.unitsSold.toLocaleString('en-IN') : '—'}
                                </span>
                              </div>
                              <div className="h-12 flex items-center border-b border-slate-200/60">
                                {prod.verified !== undefined ? (
                                  <div className="flex items-center gap-1.5">
                                    {prod.verified ? (
                                      <span className="flex items-center gap-1 bg-emerald-50 text-emerald-700 border border-emerald-200 px-2.5 py-1 rounded-lg text-xs font-bold">
                                        <CheckCircle2 size={12} className="text-emerald-500" /> Active
                                      </span>
                                    ) : (
                                      <span className="bg-amber-50 text-amber-700 border border-amber-200 px-2.5 py-1 rounded-lg text-xs font-bold">
                                        Inspection
                                      </span>
                                    )}
                                  </div>
                                ) : prod.closing !== undefined ? (
                                  <span className="text-sm font-black font-mono" style={{ color: prod.color || '#64748b' }}>
                                    {prod.closing.toLocaleString('en-IN')} {prod.unit || 'Pc'}
                                  </span>
                                ) : (
                                  <span className="text-slate-400">—</span>
                                )}
                              </div>
                            </>
                          )}
                        </div>
                      ))}
                    </>
                  );
                })()}
                
                {/* Empty placeholders removed */}

              </div>
            </div>

          </div>
        </div>
      )}
    </>,
    document.body
  );
}
