import React from 'react';
import { useCart } from '../contexts/CartContext';
import { QuantitySelector } from './QuantitySelector';
import { Button } from './Button';
import { formatPrice } from '../utils/formatPrice';
import { getProductImageUrl } from '../utils/getProductImageUrl';
import styles from './CartPopover.module.css';

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

export function CartPopover({ isOpen, onClose }: CartPopoverProps) {
  const { items, updateQuantity, removeItem } = useCart();

  if (!isOpen) return null;

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

  return (
    <>
      <div className={styles.overlay} onClick={onClose} />
      <div className={styles.popover}>
        <div className={styles.header}>
          <h2>Your Cart</h2>
          <button className={styles.closeButton} onClick={onClose} aria-label="Close cart">
            ×
          </button>
        </div>

        {items.length === 0 ? (
          <div className={styles.emptyCart}>
            <p>Your cart is empty</p>
          </div>
        ) : (
          <>
            <div className={styles.items}>
              {items.map((item) => (
                <div key={item.id} className={styles.item}>
                  <div className={styles.itemTop}>
                    <img src={getProductImageUrl(item.image)} alt={item.name} className={styles.itemImage} />
                    <div className={styles.itemDetails}>
                      <h3 className={styles.itemName}>{item.name}</h3>
                      <p className={styles.itemPrice}>{formatPrice(item.price)}</p>
                    </div>
                  </div>
                  <div className={styles.itemActions}>
                    <QuantitySelector
                      value={item.quantity}
                      onIncrement={() => updateQuantity(item.id, item.quantity + 1)}
                      onDecrement={() => updateQuantity(item.id, item.quantity - 1)}
                      min={0}
                    />
                    <button
                      className={styles.removeButton}
                      onClick={() => removeItem(item.id)}
                      aria-label="Remove item"
                    >
                      Remove
                    </button>
                  </div>
                </div>
              ))}
            </div>

            <div className={styles.footer}>
              <div className={styles.total}>
                <span>Total:</span>
                <span className={styles.totalPrice}>{formatPrice(total)}</span>
              </div>
              <Button className={styles.checkoutButton} onClick={() => alert('Checkout functionality not implemented')}>
                Go to Checkout
              </Button>
            </div>
          </>
        )}
      </div>
    </>
  );
}
