import React from 'react';
import { ShoppingCart, X, Package, Trash2, Plus, ArrowRight, Layers } from 'lucide-react';
import { useCompare } from '../contexts/CompareContext';
import { useStoreCatalogue } from '../services/storeCatalogue';

interface BulkCartDrawerProps {
  isOpen: boolean;
  onClose: () => void;
  onRequestSamples: () => void;
}

export default function BulkCartDrawer({ isOpen, onClose, onRequestSamples }: BulkCartDrawerProps) {
  const { selectedProducts, removeProduct, clearSelection, setIsComparing } = useCompare();
  const storeCat = useStoreCatalogue();

  if (!isOpen) return null;

  const handleBulkAdd = () => {
    let addedCount = 0;
    selectedProducts.forEach(prod => {
      if (prod.verified && !storeCat.has(prod.id)) {
        storeCat.add({ 
          productid: String(prod.id), 
          name: prod.name, 
          image: prod.image, 
          category: prod.category, 
          sku: prod.sku, 
          price: prod.price, 
          unit: 'All Outlets', 
          qty: 1 
        });
        addedCount++;
      }
    });
    alert(addedCount > 0 ? `Successfully added ${addedCount} product(s) to the store catalogue!` : 'Selected products are already in the catalogue or not verified.');
    if (addedCount > 0) onClose();
  };

  const handleBulkRemove = () => {
    let removedCount = 0;
    selectedProducts.forEach(prod => {
      if (storeCat.has(String(prod.id))) {
        storeCat.remove(String(prod.id));
        removedCount++;
      }
    });
    alert(removedCount > 0 ? `Successfully removed ${removedCount} product(s) from the store catalogue!` : 'None of the selected products were in the catalogue.');
    if (removedCount > 0) onClose();
  };

  return (
    <div className="fixed inset-0 z-[150] flex justify-end pointer-events-none">
      {/* Backdrop */}
      <div 
        className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm z-0 pointer-events-auto animate-in fade-in duration-300"
        onClick={onClose}
      />

      {/* Drawer */}
      <div className="w-[450px] bg-slate-50 h-full z-50 flex flex-col shadow-2xl pointer-events-auto animate-in slide-in-from-right duration-300 border-l border-slate-200 relative">
        
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-200 bg-white z-10 shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-indigo-50 flex items-center justify-center text-indigo-600 shadow-sm border border-indigo-100">
              <ShoppingCart size={20} />
            </div>
            <div>
              <h2 className="text-xl font-extrabold text-slate-900 tracking-tight">Selection Cart</h2>
              <p className="text-xs text-slate-500 font-medium">{selectedProducts.length} items ready for action</p>
            </div>
          </div>
          <div className="flex gap-2">
            <button 
              onClick={() => { clearSelection(); onClose(); }}
              className="text-xs font-bold text-slate-500 hover:text-rose-500 px-3 py-2 rounded-lg hover:bg-rose-50 transition-colors"
            >
              Clear All
            </button>
            <button 
              onClick={onClose}
              className="w-10 h-10 flex items-center justify-center rounded-xl hover:bg-slate-100 text-slate-500 transition-colors border border-transparent hover:border-slate-200"
            >
              <X size={20} />
            </button>
          </div>
        </div>

        {/* Content (Scrollable List) */}
        <div className="flex-1 overflow-y-auto custom-scrollbar p-6 space-y-3">
          {selectedProducts.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-slate-400 gap-4 opacity-50">
              <ShoppingCart size={48} strokeWidth={1} />
              <p className="text-sm font-semibold">Your cart is empty.</p>
            </div>
          ) : (
            selectedProducts.map((prod) => (
              <div key={prod.id} className="bg-white rounded-2xl p-3 flex gap-4 items-center border border-slate-200 shadow-sm relative group hover:border-[#662582]/40 transition-colors">
                <div className="w-16 h-16 rounded-xl bg-slate-100 overflow-hidden shrink-0 border border-slate-200">
                  <img src={prod.image} alt={prod.name} className="w-full h-full object-cover" />
                </div>
                <div className="flex-1 min-w-0 pr-8">
                  <span className="text-[9px] font-black uppercase tracking-wider bg-slate-100 text-slate-600 px-2 py-0.5 rounded-md inline-block mb-1">
                    {prod.category}
                  </span>
                  <h3 className="font-bold text-slate-800 text-sm truncate">{prod.name}</h3>
                  <p className="text-[10px] text-slate-400 font-mono tracking-tight mt-0.5">{prod.sku}</p>
                </div>
                <button 
                  onClick={() => removeProduct(prod.id)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 w-8 h-8 rounded-full bg-rose-50 text-rose-500 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all hover:bg-rose-100 scale-90 group-hover:scale-100"
                  title="Remove from cart"
                >
                  <Trash2 size={14} />
                </button>
              </div>
            ))
          )}
        </div>

        {/* Action Footer */}
        {selectedProducts.length > 0 && (
          <div className="p-6 bg-white border-t border-slate-200 shadow-[0_-10px_40px_rgba(0,0,0,0.05)] shrink-0 flex flex-col gap-3">
            <div className="grid grid-cols-2 gap-3">
              <button 
                onClick={handleBulkAdd}
                className="flex items-center justify-center gap-2 py-3.5 rounded-xl font-bold text-sm bg-indigo-50 text-indigo-700 hover:bg-indigo-600 hover:text-white transition-all border border-indigo-100 hover:border-indigo-600"
              >
                <Plus size={16} /> Bulk Add
              </button>
              
              <button 
                onClick={handleBulkRemove}
                className="flex items-center justify-center gap-2 py-3.5 rounded-xl font-bold text-sm bg-rose-50 text-rose-600 hover:bg-rose-500 hover:text-white transition-all border border-rose-100 hover:border-rose-500"
              >
                <Trash2 size={16} /> Bulk Remove
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
