import React, { useState, useEffect } from 'react';
import { Package, MapPin, Truck, ChevronDown, Check, X } from 'lucide-react';
import { useFiestaTenantLocations } from '../services/fiestaQueries';
import { str as fstr } from '../services/fiestaApi';

export interface TrialProduct {
  id: string | number;
  name: string;
  sku: string;
  category: string;
  price: number;
  image: string;
}

interface TrialBatchDrawerProps {
  isOpen: boolean;
  onClose: () => void;
  product: TrialProduct | null;
  tenantId?: number;
  onSuccess?: (product: TrialProduct) => void;
}

export default function TrialBatchDrawer({ isOpen, onClose, product, tenantId, onSuccess }: TrialBatchDrawerProps) {
  const [qty, setQty] = useState(5);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [selectedLocationIds, setSelectedLocationIds] = useState<string[]>([]);

  const locationsQ = useFiestaTenantLocations(tenantId);
  const stores = locationsQ.data || [];

  // Reset state when drawer opens with a new product
  useEffect(() => {
    if (isOpen) {
      setQty(5);
      setIsSubmitting(false);
      setIsSuccess(false);
      if (stores.length > 0 && selectedLocationIds.length === 0) {
        setSelectedLocationIds([String(stores[0].locationid)]);
      }
    }
  }, [isOpen, product, stores]);

  if (!isOpen || !product) return null;

  const sampleDiscount = 0.5; // 50% discount for sample
  const baseCost = qty * (product.price || 0) * Math.max(1, selectedLocationIds.length);
  const discountedCost = baseCost * (1 - sampleDiscount);

  const handleSubmit = () => {
    if (selectedLocationIds.length === 0) {
      alert("Please select at least one store delivery hub.");
      return;
    }
    setIsSubmitting(true);
    // Simulate API call
    setTimeout(() => {
      setIsSubmitting(false);
      setIsSuccess(true);
      if (onSuccess && product) {
        onSuccess(product);
      }
      // Auto close after showing success
      setTimeout(() => {
        onClose();
      }, 2000);
    }, 1500);
  };

  return (
    <div className="fixed inset-0 z-[200]">
      {/* Backdrop */}
      <div 
        className="absolute inset-0 bg-slate-900/30 backdrop-blur-sm z-0"
        onClick={onClose}
      />

      {/* Drawer */}
      <div className="absolute right-0 top-0 bottom-0 z-50 w-[400px] bg-white shadow-2xl flex flex-col border-l border-slate-200">
        
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-slate-100 bg-white z-10 shrink-0">
          <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 rounded-full bg-indigo-50 text-indigo-600 flex items-center justify-center">
              <Package size={16} />
            </div>
            <h2 className="text-lg font-extrabold text-slate-900 tracking-tight">Request Sample</h2>
          </div>
          <button 
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-slate-100 text-slate-500 transition-colors"
          >
            <X size={18} />
          </button>
        </div>

        {/* Scrollable Content */}
        <div className="flex-1 overflow-y-auto custom-scrollbar p-6 space-y-6">
          
          {/* Product Preview Card */}
          <div className="bg-slate-50 border border-slate-100 rounded-2xl p-3 flex gap-4 items-center">
            <div className="w-20 h-20 bg-white rounded-xl overflow-hidden shrink-0 border border-slate-200">
              <img src={product.image} alt={product.name} className="w-full h-full object-cover" />
            </div>
            <div className="flex-1 min-w-0">
              <span className="px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-wider bg-slate-200 text-slate-700 mb-1 inline-block">
                {product.category}
              </span>
              <h3 className="font-bold text-slate-900 text-sm leading-snug line-clamp-2">{product.name}</h3>
              <p className="text-[10px] text-slate-400 font-bold font-mono tracking-tight mt-1">{product.sku}</p>
            </div>
          </div>

          {/* Form */}
          <div className="space-y-5">
            
            {/* Quantity Selector */}
            <div>
              <label className="block text-[11px] font-bold text-slate-500 uppercase tracking-wider mb-2">Sample Quantity</label>
              <div className="flex items-center gap-3">
                {[1, 5, 10].map((amount) => (
                  <button
                    key={amount}
                    onClick={() => setQty(amount)}
                    className={`flex-1 py-2.5 rounded-xl font-bold text-sm transition-all border ${
                      qty === amount 
                        ? 'bg-indigo-50 border-indigo-200 text-indigo-700 ring-1 ring-indigo-500/20' 
                        : 'bg-white border-slate-200 text-slate-600 hover:border-indigo-300'
                    }`}
                  >
                    {amount} units
                  </button>
                ))}
              </div>
            </div>

            {/* Delivery Locations (Multi-Select) */}
            <div>
               <label className="block text-[11px] font-bold text-slate-500 uppercase tracking-wider mb-2">Delivery Hubs (Select Multiple)</label>
               
               <div className="space-y-2 max-h-48 overflow-y-auto custom-scrollbar pr-2">
                 {locationsQ.isLoading ? (
                   <div className="text-sm text-slate-500 italic p-2 border border-slate-100 rounded-lg bg-slate-50">Loading stores...</div>
                 ) : stores.length > 0 ? (
                   stores.map((store) => {
                     const sid = String(store.locationid);
                     const isSelected = selectedLocationIds.includes(sid);
                     return (
                       <div 
                         key={sid}
                         onClick={() => {
                           if (isSelected) {
                             setSelectedLocationIds(selectedLocationIds.filter(id => id !== sid));
                           } else {
                             setSelectedLocationIds([...selectedLocationIds, sid]);
                           }
                         }}
                         className={`flex items-center gap-3 p-3 rounded-xl border cursor-pointer transition-all ${
                           isSelected 
                             ? 'bg-indigo-50 border-indigo-200 shadow-sm' 
                             : 'bg-white border-slate-200 hover:border-indigo-300'
                         }`}
                       >
                         <div className={`w-5 h-5 rounded flex items-center justify-center shrink-0 border transition-colors ${
                           isSelected ? 'bg-indigo-600 border-indigo-600 text-white' : 'border-slate-300 bg-white'
                         }`}>
                           {isSelected && <Check size={12} strokeWidth={3} />}
                         </div>
                         <div className="flex-1 min-w-0">
                           <h4 className={`font-bold text-sm truncate ${isSelected ? 'text-indigo-900' : 'text-slate-900'}`}>
                             {fstr(store.locationname)}
                           </h4>
                           <p className="text-xs text-slate-500 truncate mt-0.5">
                             {fstr(store.suburb) || fstr(store.city) || 'Main Outlet'}
                           </p>
                         </div>
                       </div>
                     );
                   })
                 ) : (
                   <div className="text-sm text-slate-500 italic p-2 border border-slate-100 rounded-lg bg-slate-50">No stores found</div>
                 )}
               </div>

            </div>

          </div>
        </div>

        {/* Footer actions */}
        <div className="p-6 border-t border-slate-100 bg-white shrink-0">
          
          <div className="mb-4 bg-slate-50 rounded-xl p-3 border border-slate-100">
            <div className="flex justify-between text-xs mb-1.5">
              <span className="text-slate-500 font-medium">Base Price ({qty} × ₹{product.price || 0})</span>
              <span className="font-mono text-slate-700">₹{baseCost.toLocaleString('en-IN')}</span>
            </div>
            <div className="flex justify-between text-xs mb-2">
              <span className="text-indigo-600 font-bold">Sample Discount (50%)</span>
              <span className="font-mono text-indigo-600 font-bold">-₹{(baseCost * sampleDiscount).toLocaleString('en-IN')}</span>
            </div>
            <div className="pt-2 border-t border-slate-200 flex justify-between items-end mt-2">
              <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Total Est. Cost</span>
              <span className="text-xl font-black text-slate-900 font-mono">₹{discountedCost.toLocaleString('en-IN')}</span>
            </div>
          </div>

          <button
            onClick={handleSubmit}
            disabled={isSubmitting || isSuccess}
            className={`w-full relative overflow-hidden flex items-center justify-center gap-2 py-3.5 rounded-xl text-sm font-bold transition-all shadow-md ${
              isSuccess 
                ? 'bg-emerald-500 text-white hover:bg-emerald-600 shadow-emerald-500/20' 
                : 'bg-[#0f172a] text-white hover:bg-slate-800 hover:-translate-y-0.5 shadow-slate-900/20'
            }`}
          >
            {isSubmitting ? (
              <div className="flex items-center gap-2">
                <span className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin" />
                Processing...
              </div>
            ) : isSuccess ? (
              <div className="flex items-center gap-2 animate-in fade-in zoom-in duration-300">
                <Check size={18} strokeWidth={3} />
                Request Sent
              </div>
            ) : (
              <>
                <Truck size={18} /> Request Trial Batch
              </>
            )}
          </button>
        </div>

      </div>
    </div>
  );
}
