import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Trash2, ShoppingBag, ArrowRight } from 'lucide-react';
import { useCartStore } from '@/lib/cart/store';
import { formatPrice } from '@/lib/currency';
import { Button } from '@/components/ui/button';
import { apiClient } from '@/lib/api/client';

export function MiniCartDrawer() {
  const { cart, isOpen, closeCart, updateQuantity, removeItem, setCart } = useCartStore();
  const navigate = useNavigate();

  // Close cart when pressing Escape
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') closeCart();
    };
    window.addEventListener('keydown', handleEscape);
    return () => window.removeEventListener('keydown', handleEscape);
  }, [closeCart]);

  // Lock body scroll when cart is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isOpen]);

  // Update quantity via API
  const handleUpdateQuantity = async (key: string, newQuantity: number) => {
    if (newQuantity < 1) return;
    updateQuantity(key, newQuantity);
    try {
      const response = await apiClient.post<{ cart: any }>('/woonoow/v1/cart/update', {
        key,
        quantity: newQuantity,
      });
      if (response.cart) setCart(response.cart);
    } catch (error) {
      console.error('Failed to update cart', error);
    }
  };

  // Remove item via API
  const handleRemoveItem = async (key: string) => {
    removeItem(key);
    try {
      const response = await apiClient.post<{ cart: any }>('/woonoow/v1/cart/remove', { key });
      if (response.cart) setCart(response.cart);
    } catch (error) {
      console.error('Failed to remove item', error);
    }
  };

  const handleCheckout = () => {
    closeCart();
    navigate('/checkout');
  };

  const cartTotal = cart.items.reduce((total, item) => total + item.price * item.quantity, 0);

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={closeCart}
            className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[10000]"
          />

          {/* Drawer */}
          <motion.div
            initial={{ x: '100%' }}
            animate={{ x: 0 }}
            exit={{ x: '100%' }}
            transition={{ type: 'spring', damping: 25, stiffness: 200 }}
            className="fixed inset-y-0 right-0 w-full max-w-md bg-white dark:bg-background shadow-2xl z-[10001] flex flex-col"
          >
            {/* Header */}
            <div className="flex items-center justify-between p-4 sm:p-6 border-b">
              <h2 className="text-xl font-bold flex items-center gap-2">
                <ShoppingBag className="w-5 h-5" />
                Your Cart
                <span className="text-sm font-normal text-muted-foreground ml-2">
                  ({cart.items.length} {cart.items.length === 1 ? 'item' : 'items'})
                </span>
              </h2>
              <Button variant="ghost" size="icon" onClick={closeCart} className="rounded-full">
                <X className="w-5 h-5" />
              </Button>
            </div>

            {/* Cart Items */}
            <div className="flex-1 overflow-y-auto p-4 sm:p-6">
              {cart.items.length === 0 ? (
                <div className="h-full flex flex-col items-center justify-center text-center space-y-4">
                  <div className="w-20 h-20 bg-muted rounded-full flex items-center justify-center">
                    <ShoppingBag className="w-10 h-10 text-muted-foreground" />
                  </div>
                  <h3 className="text-lg font-semibold">Your cart is empty</h3>
                  <p className="text-muted-foreground">Looks like you haven't added anything yet.</p>
                  <Button onClick={closeCart} className="mt-4">
                    Continue Shopping
                  </Button>
                </div>
              ) : (
                <div className="space-y-6">
                  {/* Free Shipping Motivator (Example Placeholder) */}
                  <div className="bg-primary/10 p-3 rounded-lg text-sm text-center font-medium text-primary">
                    You're $15 away from <strong>Free Shipping!</strong>
                  </div>

                  {cart.items.map((item) => (
                    <motion.div 
                      key={item.key} 
                      layout
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, scale: 0.9 }}
                      className="flex gap-4"
                    >
                      {/* Image */}
                      <div className="w-20 h-20 rounded-md overflow-hidden bg-muted flex-shrink-0">
                        {item.image ? (
                          <img src={item.image} alt={item.name} className="w-full h-full object-cover" />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center text-muted-foreground">
                            <ShoppingBag className="w-8 h-8 opacity-20" />
                          </div>
                        )}
                      </div>

                      {/* Details */}
                      <div className="flex flex-col justify-between flex-1">
                        <div className="flex justify-between items-start">
                          <div>
                            <h4 className="font-medium line-clamp-2 text-sm">{item.name}</h4>
                            {item.attributes && (
                              <div className="text-xs text-muted-foreground mt-1 space-y-0.5">
                                {Object.entries(item.attributes).map(([key, value]) => (
                                  <div key={key}>
                                    <span className="font-medium">{key}:</span> {value}
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                          <button
                            onClick={() => handleRemoveItem(item.key)}
                            className="text-muted-foreground hover:text-destructive p-1"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>

                        <div className="flex items-center justify-between mt-2">
                          {/* Quantity Selector */}
                          <div className="flex items-center border rounded-md">
                            <button
                              onClick={() => handleUpdateQuantity(item.key, item.quantity - 1)}
                              className="px-2 py-1 hover:bg-muted transition-colors text-sm"
                            >
                              -
                            </button>
                            <span className="px-2 py-1 text-sm font-medium w-8 text-center">
                              {item.quantity}
                            </span>
                            <button
                              onClick={() => handleUpdateQuantity(item.key, item.quantity + 1)}
                              className="px-2 py-1 hover:bg-muted transition-colors text-sm"
                            >
                              +
                            </button>
                          </div>
                          <span className="font-semibold text-sm">
                            {formatPrice(item.price * item.quantity)}
                          </span>
                        </div>
                      </div>
                    </motion.div>
                  ))}
                </div>
              )}
            </div>

            {/* Footer */}
            {cart.items.length > 0 && (
              <div className="border-t p-4 sm:p-6 bg-gray-50/50 dark:bg-card">
                <div className="flex justify-between items-center mb-4">
                  <span className="text-sm font-medium text-muted-foreground">Subtotal</span>
                  <span className="text-lg font-bold">{formatPrice(cartTotal)}</span>
                </div>
                
                <p className="text-xs text-muted-foreground text-center mb-4">
                  Taxes and shipping calculated at checkout
                </p>

                <div className="space-y-3">
                  <Button onClick={handleCheckout} className="w-full py-6 text-lg" size="lg">
                    Checkout <ArrowRight className="ml-2 w-5 h-5" />
                  </Button>
                  
                  {/* Express Checkout Placeholders */}
                  <div className="grid grid-cols-2 gap-2 mt-2">
                    <Button variant="outline" className="w-full flex gap-2 border-black dark:border-border hover:bg-gray-100 dark:hover:bg-accent">
                      <svg viewBox="0 0 384 512" className="w-3 h-3"><path d="M318.7 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7C63.3 141.2 4 184.8 4 273.5q0 39.3 14.4 81.2c12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zM201.2 43.6C227.1 12.8 244 0 244 0c-4.2 32.2-18.6 60.1-41.2 81.6-21.7 21-50.6 34.6-78.6 34.6-1.5-27.1 14.1-53.7 32.6-72.6z"/></svg>
                      Pay
                    </Button>
                    <Button variant="outline" className="w-full flex gap-2 border-[#4285F4] text-[#4285F4] hover:bg-blue-50 dark:hover:bg-accent">
                      <svg viewBox="0 0 488 512" className="w-3 h-3" fill="currentColor"><path d="M488 261.8C488 403.3 391.1 504 248 504 110.8 504 0 393.2 0 256S110.8 8 248 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9C258.5 52.6 94.3 116.6 94.3 256c0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9H248v-85.3h236.1c2.3 12.7 3.9 24.9 3.9 41.4z"/></svg>
                      Pay
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
