'use client';

import { useState, useEffect } from 'react';
import { useCartStore } from '@/stores/cartStore';

function IconX({ size = 18 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M18 6 6 18"/><path d="M6 6l12 12"/>
    </svg>
  );
}

function IconMinus({ size = 14 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14"/>
    </svg>
  );
}

function IconPlus({ size = 14 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 5v14"/><path d="M5 12h14"/>
    </svg>
  );
}

function IconTrash({ size = 14 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>
    </svg>
  );
}

function IconShoppingBag({ size = 20 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" x2="21" y1="6" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/>
    </svg>
  );
}

export function CartDrawer() {
  const { items, isOpen, closeCart, removeItem, updateQuantity, getTotal, getItemCount, clearCart } = useCartStore();
  const total = getTotal();
  const count = getItemCount();

  if (!isOpen) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 z-50"
        style={{ background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(4px)' }}
        onClick={closeCart}
      />

      {/* Drawer */}
      <div
        className="fixed top-0 right-0 bottom-0 z-50 w-full max-w-md flex flex-col"
        style={{ background: 'var(--bg-secondary)', borderLeft: '1px solid var(--border-dark)' }}
      >
        {/* Header */}
        <div
          className="flex items-center justify-between px-5 py-4 shrink-0"
          style={{ borderBottom: '1px solid var(--border-dark)' }}
        >
          <div className="flex items-center gap-2">
            <IconShoppingBag />
            <h2 className="font-impact text-base" style={{ color: 'var(--color-gold)' }}>
              PANIER
            </h2>
            {count > 0 && (
              <span
                className="px-2 py-0.5 rounded-full text-[10px] font-bold"
                style={{ background: 'var(--color-red)', color: 'white' }}
              >
                {count}
              </span>
            )}
          </div>
          <button onClick={closeCart} className="p-1.5 rounded-lg hover:bg-white/5 transition-colors">
            <IconX />
          </button>
        </div>

        {/* Items */}
        <div className="flex-1 overflow-y-auto px-5 py-4 space-y-3">
          {items.length === 0 ? (
            <div className="text-center py-16">
              <div className="mb-4 opacity-20">
                <IconShoppingBag size={48} />
              </div>
              <p className="text-sm" style={{ color: 'var(--text-muted)' }}>
                Votre panier est vide
              </p>
              <button
                onClick={closeCart}
                className="mt-4 px-4 py-2 rounded-lg text-xs btn-ghost"
              >
                Continuer mes achats
              </button>
            </div>
          ) : (
            items.map((item) => (
              <div
                key={`${item.productId}-${item.color}-${item.size}`}
                className="flex gap-3 p-3 rounded-lg"
                style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}
              >
                {/* Product image placeholder */}
                <div
                  className="w-14 h-14 rounded-lg flex items-center justify-center text-xl flex-shrink-0"
                  style={{ background: 'var(--bg-surface-bright)' }}
                >
                  {item.image}
                </div>

                <div className="flex-1 min-w-0">
                  <h4 className="text-xs font-medium truncate" style={{ color: 'var(--text-primary)' }}>
                    {item.name}
                  </h4>
                  <p className="text-[10px] mt-0.5" style={{ color: 'var(--text-muted)' }}>
                    {item.brand}
                    {item.color && ` — ${item.color}`}
                    {item.size && ` — ${item.size}`}
                  </p>

                  <div className="flex items-center justify-between mt-2">
                    {/* Quantity controls */}
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => updateQuantity(item.productId, item.quantity - 1, item.color, item.size)}
                        className="w-6 h-6 rounded flex items-center justify-center hover:bg-white/10 transition-colors"
                        style={{ border: '1px solid var(--border-dark)' }}
                      >
                        <IconMinus />
                      </button>
                      <span className="w-7 text-center text-xs font-bold" style={{ color: 'var(--text-primary)' }}>
                        {item.quantity}
                      </span>
                      <button
                        onClick={() => updateQuantity(item.productId, item.quantity + 1, item.color, item.size)}
                        className="w-6 h-6 rounded flex items-center justify-center hover:bg-white/10 transition-colors"
                        style={{ border: '1px solid var(--border-dark)' }}
                      >
                        <IconPlus />
                      </button>
                    </div>

                    {/* Price */}
                    <span className="text-xs font-bold" style={{ color: 'var(--color-gold)' }}>
                      {(item.price * item.quantity).toFixed(2)} &euro;
                    </span>

                    {/* Remove */}
                    <button
                      onClick={() => removeItem(item.productId, item.color, item.size)}
                      className="p-1 rounded hover:bg-red-500/10 transition-colors"
                      style={{ color: 'var(--color-red-light)' }}
                    >
                      <IconTrash />
                    </button>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>

        {/* Footer — Total + Checkout */}
        {items.length > 0 && (
          <div
            className="shrink-0 px-5 py-4 space-y-3"
            style={{ borderTop: '1px solid var(--border-dark)', background: 'var(--bg-panel)' }}
          >
            {/* Subtotal */}
            <div className="flex justify-between items-center">
              <span className="text-xs" style={{ color: 'var(--text-muted)' }}>Sous-total</span>
              <span className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>
                {total.toFixed(2)} &euro;
              </span>
            </div>

            <div className="flex justify-between items-center">
              <span className="text-xs" style={{ color: 'var(--text-muted)' }}>Livraison</span>
              <span className="text-xs" style={{ color: total >= 50 ? '#4ade80' : 'var(--text-secondary)' }}>
                {total >= 50 ? 'Offerte' : '4.90 \u20ac'}
              </span>
            </div>

            <div className="section-divider-red" />

            <div className="flex justify-between items-center">
              <span className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>Total</span>
              <span className="text-lg font-bold text-gold-gradient">
                {(total + (total >= 50 ? 0 : 4.90)).toFixed(2)} &euro;
              </span>
            </div>

            {total < 50 && (
              <p className="text-[10px] text-center" style={{ color: 'var(--text-muted)' }}>
                Plus que {(50 - total).toFixed(2)}&euro; pour la livraison gratuite
              </p>
            )}

            {/* Checkout button */}
            <button className="w-full py-3 rounded-lg text-sm btn-primary animate-pulse-glow">
              Passer commande
            </button>

            {/* Clear cart */}
            <button
              onClick={clearCart}
              className="w-full py-2 text-[10px] text-center transition-colors hover:underline"
              style={{ color: 'var(--text-muted)' }}
            >
              Vider le panier
            </button>
          </div>
        )}
      </div>
    </>
  );
}

/** Cart icon button for NavBar or Shop page */
export function CartButton() {
  const { toggleCart, getItemCount } = useCartStore();
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  const count = mounted ? getItemCount() : 0;

  return (
    <button
      onClick={toggleCart}
      className="relative p-2 rounded-lg transition-all hover:bg-white/5"
      style={{ color: 'var(--text-secondary)' }}
    >
      <IconShoppingBag size={20} />
      {count > 0 && (
        <span
          className="absolute -top-1 -right-1 rounded-full text-[9px] font-bold flex items-center justify-center"
          style={{
            background: 'var(--color-red)',
            color: 'white',
            minWidth: '18px',
            height: '18px',
          }}
        >
          {count}
        </span>
      )}
    </button>
  );
}
