import { useCartStore } from '@/stores/cartStore';
import { Button } from '@/components/ui/button';
import { ShoppingCart, Trash2 } from 'lucide-react';
import { marketplaceService } from '@/services/marketplaceService';
import { useToast } from '@/hooks/useToast';
import { useState } from 'react';
import { useAuthStore } from '@/stores/auth';
import { Dialog } from '@/components/ui/dialog';

// FE-PAGE-006: Complete Marketplace page implementation - Cart Component

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

export function Cart({ isOpen, onClose }: CartProps) {
  const { items, removeItem, updateQuantity, clearCart, getTotal } =
    useCartStore();
  const { isAuthenticated } = useAuthStore();
  const toast = useToast();
  const [isCheckingOut, setIsCheckingOut] = useState(false);

  const formatPrice = (price: number, currency: string) => {
    return new Intl.NumberFormat('fr-FR', {
      style: 'currency',
      currency: currency || 'EUR',
    }).format(price);
  };

  const handleCheckout = async () => {
    if (!isAuthenticated) {
      toast.error('Please log in to checkout');
      return;
    }

    if (items.length === 0) {
      toast.error('Cart is empty');
      return;
    }

    try {
      setIsCheckingOut(true);
      const orderItems = items.map((item) => ({
        product_id: item.product.id,
      }));
      await marketplaceService.createOrder(orderItems);
      toast.success('Order placed successfully!');
      clearCart();
      onClose();
    } catch (error: any) {
      const errorMessage =
        error.response?.data?.error ||
        error.response?.data?.message ||
        error.message ||
        'Failed to place order';
      toast.error(errorMessage);
    } finally {
      setIsCheckingOut(false);
    }
  };

  return (
    <Dialog open={isOpen} onClose={onClose} title="Shopping Cart" size="lg">
      <div className="space-y-4">
        {items.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            <ShoppingCart className="h-12 w-12 mx-auto mb-4 opacity-50" />
            <p>Your cart is empty</p>
          </div>
        ) : (
          <>
            <div className="max-h-96 overflow-y-auto space-y-2">
              {items.map((item) => (
                <div
                  key={item.product.id}
                  className="flex items-center justify-between p-3 border rounded-lg"
                >
                  <div className="flex-1">
                    <h4 className="font-medium">{item.product.title}</h4>
                    <p className="text-sm text-muted-foreground">
                      {formatPrice(item.product.price, item.product.currency)} ×{' '}
                      {item.quantity}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() =>
                        updateQuantity(item.product.id, item.quantity - 1)
                      }
                    >
                      -
                    </Button>
                    <span className="w-8 text-center">{item.quantity}</span>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() =>
                        updateQuantity(item.product.id, item.quantity + 1)
                      }
                    >
                      +
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removeItem(item.product.id)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
            <div className="border-t pt-4 space-y-4">
              <div className="flex justify-between text-lg font-bold">
                <span>Total:</span>
                <span>
                  {items.length > 0
                    ? formatPrice(getTotal(), items[0].product.currency)
                    : '€0.00'}
                </span>
              </div>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  onClick={clearCart}
                  className="flex-1"
                >
                  Clear Cart
                </Button>
                <Button
                  onClick={handleCheckout}
                  disabled={isCheckingOut}
                  className="flex-1"
                >
                  {isCheckingOut ? 'Processing...' : 'Checkout'}
                </Button>
              </div>
            </div>
          </>
        )}
      </div>
    </Dialog>
  );
}

