'use client';

import React, { useEffect, useState, useRef, useCallback } from 'react';
import Link from 'next/link';
import { useCart } from '@/context/CartContext';
import { useSiteSettings } from '@/context/SiteSettingsContext';
import { useAuth } from '@/context/AuthContext';
import { 
  X, 
  Plus, 
  Minus, 
  ChevronLeft, 
  ChevronRight, 
  ArrowRight,
  Check
} from 'lucide-react';
import api from '@/lib/api';

interface Product {
  id: number;
  name: string;
  slug: string;
  price: number;
  image_url: string;
}

export const CartDrawer: React.FC = () => {
  const { 
    cartItems, 
    subtotal, 
    updateQuantity, 
    removeItem,
    addToCart,
    cartOpen, 
    setCartOpen 
  } = useCart();
  const { formatPrice } = useSiteSettings();
  const { user } = useAuth();
  const isReseller = user?.role === 'reseller';

  // For both resellers and customers, use CartContext unified values
  const displayItems = cartItems;
  const displaySubtotal = subtotal;
  const displayCount = cartItems.reduce((acc, item) => acc + item.quantity, 0);
  const resellerProfit = isReseller
    ? cartItems.reduce((acc, item) => acc + Math.max(0, item.price - Number(item.reseller_price || 0)) * item.quantity, 0)
    : 0;


  const [crossSellProducts, setCrossSellProducts] = useState<Product[]>([]);
  const sliderRef = useRef<HTMLDivElement>(null);

  // Track which cross-sell product IDs are in "added" state for instant button feedback
  const [addedIds, setAddedIds] = useState<Set<number>>(new Set());

  // Fetch cross-sell products once when drawer first opens, then cache
  const crossSellFetched = useRef(false);
  useEffect(() => {
    if (!cartOpen || crossSellFetched.current) return;
    crossSellFetched.current = true;

    api.get('/api/products?limit=6').then((res) => {
      const items = res.data.data || [];
      if (Array.isArray(items)) setCrossSellProducts(items);
    }).catch(() => {
      setCrossSellProducts([
        { id: 991, name: 'Himsagar Mango-2 kg', slug: 'himsagar-mango', price: 240, image_url: '/images/placeholder.jpg' },
        { id: 992, name: 'Premium Gawa Ghee 500g', slug: 'gawa-ghee', price: 850, image_url: '/images/placeholder.jpg' },
      ]);
    });
  }, [cartOpen]);

  // ── Instant qty change ───────────────────────────────────────────────────────────
  const handleQtyChange = useCallback((itemId: number, currentQty: number, maxStock: number, change: number) => {
    const newQty = currentQty + change;
    if (newQty <= 0) {
      removeItem(itemId);
      return;
    }
    if (newQty > maxStock) return;
    updateQuantity(itemId, newQty);
  }, [removeItem, updateQuantity]);

  // ── Instant remove ───────────────────────────────────────────────────────────────────
  const handleRemove = useCallback((itemId: number) => {
    removeItem(itemId);
  }, [removeItem]);

  // ── Quick Add from "You May Also Like" — fully instant ───────────────────────
  const handleQuickAdd = useCallback((product: Product) => {
    // Show "added" checkmark immediately on the button
    setAddedIds((prev) => {
      const next = new Set(prev);
      next.add(product.id);
      return next;
    });
    setTimeout(() => {
      setAddedIds((prev) => {
        const next = new Set(prev);
        next.delete(product.id);
        return next;
      });
    }, 1800);

    // Fire and forget — CartContext optimistic update handles cart state instantly
    addToCart(product.id, null, 1, true, product).catch((err) => {
      console.error('Quick add failed', err);
    });
  }, [addToCart]);

  const scrollSlider = (direction: 'left' | 'right') => {
    if (sliderRef.current) {
      const { scrollLeft, clientWidth } = sliderRef.current;
      sliderRef.current.scrollTo({
        left: direction === 'left' ? scrollLeft - clientWidth * 0.75 : scrollLeft + clientWidth * 0.75,
        behavior: 'smooth',
      });
    }
  };



  return (
    <>
      {/* Main Cart Drawer Wrapper (acting as backdrop) */}
      <div 
        className={`fixed inset-0 z-50 bg-black/40 backdrop-blur-xs transition-opacity duration-300 cursor-pointer flex justify-end ${
          cartOpen ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'
        }`}
        onClick={() => setCartOpen(false)}
      >
        {/* Main Drawer Panel sliding from right */}
        <div 
          className={`w-full lg:max-w-md bg-white h-full flex flex-col shadow-2xl transition-transform duration-300 ease-out ${
            cartOpen ? 'translate-x-0' : 'translate-x-full'
          }`}
          onClick={(e) => e.stopPropagation()}
          style={{ fontFamily: 'var(--font-open-sans), sans-serif' }}
        >
        
        {/* Header */}
        <div className="px-4 py-4 border-b border-slate-100 flex items-center justify-between bg-white shrink-0">
          <span className="text-sm font-medium text-slate-700 tracking-wider">SHOPPING CART</span>
          <button 
            onClick={() => setCartOpen(false)} 
            className="text-xs font-normal text-slate-500 hover:text-slate-800 flex items-center gap-1 cursor-pointer focus:outline-none"
          >
            <span>Close</span>
            <ArrowRight className="h-4 w-4" />
          </button>
        </div>

        {/* Scrollable Item List */}
        <div className="flex-1 overflow-y-auto p-4 space-y-5 scrollbar-none bg-slate-50/30">
          


          {/* Cart Items */}
          {displayItems.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-20 text-center space-y-4">
              <div className="relative flex items-center justify-center h-28 w-28 mx-auto">
                <div className="absolute inset-0 bg-blue-50/50 rounded-full scale-95" />
                <svg className="h-14 w-14 text-blue-500 relative" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.8">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
                </svg>
                <div className="absolute top-5 right-5 h-5 w-5 rounded-full bg-blue-500 border-2 border-white flex items-center justify-center text-white">
                  <X className="h-3 w-3 stroke-[3]" />
                </div>
              </div>
              <h3 className="text-sm font-semibold text-slate-700">No items in your cart!</h3>
            </div>
          ) : (
            <div className="space-y-3">
              {displayItems.map((item: any) => {
                // For regular customers: skip optimistic placeholder items
                if (!isReseller && item.id < 0) return null;

                const itemId = isReseller ? item.product_id : item.id;
                const imageUrl = item.image_url && item.image_url.startsWith('http')
                  ? item.image_url
                  : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}${item.image_url || ''}`;
                const maxStock = isReseller ? 9999 : item.stock;

                return (
                  <div 
                    key={itemId} 
                    className="bg-white border border-slate-100 rounded-2xl p-3 flex items-center gap-3 relative shadow-xs group"
                  >
                    {/* Item Image */}
                    <div className="h-16 w-16 bg-slate-50 border border-slate-100 rounded-xl overflow-hidden flex items-center justify-center p-1.5 flex-shrink-0">
                      <img src={imageUrl} alt={item.name} className="max-h-full max-w-full object-contain" />
                    </div>

                    {/* Details */}
                    <div className="flex-1 min-w-0 text-left space-y-1">
                      <h4 className="text-sm font-medium text-slate-800 truncate pr-5 font-sans">
                        {item.name}
                      </h4>

                      {/* Options (only for regular cart items) */}
                      {!isReseller && item.options && Object.keys(item.options).length > 0 && (
                        <div className="flex gap-1.5 flex-wrap">
                          {Object.entries(item.options).map(([key, val]) => (
                            <span key={key} className="text-[8px] font-medium bg-slate-55 border border-slate-100 text-slate-500 px-1.5 py-0.5 rounded">
                              {key}: {val as string}
                            </span>
                          ))}
                        </div>
                      )}

                      {/* Qty + Price row */}
                      <div className="flex items-center gap-2 pt-1">
                        <div className="flex items-center border border-slate-200 rounded-lg overflow-hidden bg-slate-50 h-7 shrink-0">
                          <button
                            onClick={() => handleQtyChange(itemId, item.quantity, maxStock, -1)}
                            className="px-2 text-slate-500 active:bg-slate-200 font-normal text-xs focus:outline-none select-none"
                          >
                            <Minus className="h-3 w-3" />
                          </button>
                          <span className="px-1 text-xs font-normal text-slate-800 w-5 text-center tabular-nums">
                            {item.quantity}
                          </span>
                          <button
                            onClick={() => handleQtyChange(itemId, item.quantity, maxStock, 1)}
                            className="px-2 text-slate-500 active:bg-slate-200 font-normal text-xs focus:outline-none select-none"
                          >
                            <Plus className="h-3 w-3" />
                          </button>
                        </div>
                        <span className="text-xs text-slate-400">x</span>
                        {isReseller ? (
                          <div className="flex flex-col gap-0.5 text-left pl-1">
                            <span className="text-xs text-slate-500 font-normal">
                              Reseller Cost: {formatPrice(item.wholesale_price)}
                            </span>
                            <span className="text-xs text-slate-700 font-medium">
                              Retail Price: {formatPrice(item.price)}
                            </span>
                            <span className="text-xs text-emerald-700 font-medium bg-emerald-50 px-1 py-0.5 rounded border border-emerald-100/50 mt-0.5 w-fit">
                              Profit: {formatPrice(Math.max(0, item.price - item.wholesale_price) * item.quantity)}
                            </span>
                          </div>
                        ) : (
                          <>
                            <span className="text-xs font-normal text-slate-700">{formatPrice(item.price)}</span>
                            <span className="text-xs text-slate-400">=</span>
                            <span className="text-xs font-medium text-secondary tabular-nums">
                              {formatPrice(item.price * item.quantity)}
                            </span>
                          </>
                        )}
                      </div>
                    </div>

                    {/* Remove button */}
                    <button 
                      onClick={() => handleRemove(itemId)}
                      className="absolute top-3 right-3 text-slate-400 hover:text-rose-500 focus:outline-none p-0.5 active:scale-90 transition-transform"
                    >
                      <X className="h-4.5 w-4.5" />
                    </button>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer (sticky bottom) */}
        <div className="p-4 bg-[#f8f9fa] space-y-2.5 shrink-0 shadow-[0_-4px_12px_rgba(0,0,0,0.04)] z-10">
          
          {/* You May Also Like Slider */}
          {crossSellProducts.length > 0 && (
            <div className="space-y-2 pb-0">
              <div className="flex items-center justify-between">
                <div className="relative">
                  <h4 className="text-xs font-medium text-slate-700 tracking-wide pb-1 font-sans">
                    You May Also Like
                  </h4>
                  <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-secondary" />
                </div>
                <div className="flex items-center gap-1.5">
                  <button 
                    onClick={() => scrollSlider('left')} 
                    className="h-6 w-6 rounded-full bg-secondary text-white flex items-center justify-center hover:bg-secondary-dark transition-colors focus:outline-none cursor-pointer"
                  >
                    <ChevronLeft className="h-3.5 w-3.5 stroke-[2]" />
                  </button>
                  <button 
                    onClick={() => scrollSlider('right')} 
                    className="h-6 w-6 rounded-full bg-secondary text-white flex items-center justify-center hover:bg-secondary-dark transition-colors focus:outline-none cursor-pointer"
                  >
                    <ChevronRight className="h-3.5 w-3.5 stroke-[2]" />
                  </button>
                </div>
              </div>

              {/* Slider */}
              <div 
                ref={sliderRef}
                className="flex gap-3 overflow-x-auto pb-1 scroll-smooth scrollbar-none snap-x snap-mandatory"
              >
                {crossSellProducts.map((product) => {
                  const resolvedUrl = product.image_url.startsWith('http')
                    ? product.image_url
                    : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}${product.image_url}`;
                  const isAdded = addedIds.has(product.id);

                  return (
                    <div 
                      key={product.id}
                      className="w-[240px] shrink-0 snap-start bg-white border border-slate-100 rounded-2xl p-2.5 flex items-center gap-2.5 shadow-xs text-left"
                    >
                      <div className="h-14 w-14 bg-slate-50 border border-slate-100 rounded-xl overflow-hidden flex items-center justify-center p-1.5 flex-shrink-0">
                        <img src={resolvedUrl} alt={product.name} className="max-h-full max-w-full object-contain" />
                      </div>
                      <div className="flex-1 min-w-0 space-y-1">
                        <h5 className="text-[12px] font-medium text-slate-700 truncate font-sans">
                          {product.name}
                        </h5>
                        <div className="flex items-center justify-between pt-0.5">
                          <span className="text-[12px] font-normal text-slate-700 font-sans">{formatPrice(product.price)}</span>
                          {/* Instant feedback Add button */}
                          <button
                            onClick={() => handleQuickAdd(product)}
                            className={`text-[12px] font-medium px-2.5 py-1 rounded-lg transition-all duration-200 cursor-pointer flex items-center gap-0.5 focus:outline-none active:scale-90 font-sans ${
                              isAdded
                                ? 'bg-emerald-500 text-white'
                                : 'bg-secondary hover:bg-secondary-dark text-white'
                            }`}
                          >
                            {isAdded ? (
                              <>
                                <Check className="h-2.5 w-2.5 stroke-[2]" />
                                <span>Added</span>
                              </>
                            ) : (
                              <>
                                <Plus className="h-2.5 w-2.5 stroke-[2]" />
                                <span>Add</span>
                              </>
                            )}
                          </button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Total */}
          <div className="flex flex-col gap-1 border-t border-slate-200/60 pt-2 text-right">
            <div className="flex justify-between items-center text-xs font-normal text-slate-500">
              <span>Sub total:</span>
              <span>{formatPrice(displaySubtotal)}</span>
            </div>
            {isReseller && resellerProfit > 0 && (
              <div className="flex justify-between items-center text-xs font-medium text-emerald-600">
                <span>Reseller Profit:</span>
                <span>+{formatPrice(resellerProfit)}</span>
              </div>
            )}
            <div className="flex justify-between items-center text-xs font-normal text-slate-500">
              <span>Delivery cost:</span>
              <span>{formatPrice(0)}</span>
            </div>
            <div className="flex justify-between items-center border-t border-slate-100 pt-1">
              <span className="text-sm font-medium text-slate-700">Total:</span>
              <span className="text-sm font-medium text-slate-900 tabular-nums transition-all duration-150">
                {formatPrice(displaySubtotal)}
              </span>
            </div>
          </div>

          {/* Checkout Button */}
          <div className="flex justify-center w-full">
            <Link
              href={displayCount > 0 ? "/checkout" : "#"}
              onClick={(e) => {
                if (displayCount === 0) { e.preventDefault(); return; }
                setCartOpen(false);
              }}
              className={`btn shake-btn btn-primary btn-rounded rsi-shake custom-checkout-btn ${
                displayCount === 0 ? 'btn-disabled' : ''
              }`}
            >
              CHECKOUT
            </Link>
          </div>
        </div>
      </div>
    </div>

      <style>{`
        @keyframes rsi-shake {
          0%, 80%, 100% { transform: rotate(0deg); }
          82%, 86%, 90%, 94%, 98% { transform: rotate(-2deg); }
          84%, 88%, 92%, 96% { transform: rotate(2deg); }
        }
        .rsi-shake { animation: rsi-shake 2s infinite ease-in-out; }
        .custom-checkout-btn {
          background-color: var(--color-secondary) !important;
          color: #FFFFFF !important;
          font-family: "Open Sans", sans-serif, system-ui !important;
          font-size: 14px !important;
          font-weight: 500 !important;
          height: 37px !important;
          width: 333px !important;
          padding: 10px !important;
          border-radius: 9999px !important;
          display: inline-flex !important;
          align-items: center !important;
          justify-content: center !important;
          text-align: center !important;
          transition: all 0.2s ease-in-out !important;
          text-transform: uppercase !important;
          text-decoration: none !important;
        }
        .custom-checkout-btn.btn-disabled {
          background-color: #cbd5e1 !important;
          color: #94a3b8 !important;
          cursor: not-allowed !important;
          pointer-events: none !important;
        }
        .custom-checkout-btn:hover:not(.btn-disabled) {
          background-color: var(--color-secondary-dark) !important;
        }
      `}</style>
    </>
  );
};

function numberWithCommas(x: number | null | undefined) {
  if (x === null || x === undefined || isNaN(Number(x))) return '0';
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
