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, useRef } from 'react';
import { useAuthStore } from '@/features/auth/store/authStore';
import { Dialog } from '@/components/ui/dialog';
import { parseApiError } from '@/utils/apiErrorHandler';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';

// 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 [validationError, setValidationError] = useState<string | null>(null);
  const [mutationError, setMutationError] = useState<Error | null>(null);
  const [retryCount, setRetryCount] = useState(0);
  const lastMutationRef = useRef<(() => Promise<void>) | null>(null);

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

  const handleCheckout = async () => {
    setValidationError(null);
    setMutationError(null);

    if (!isAuthenticated) {
      setValidationError('Please log in to checkout');
      return;
    }

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

    // Action 3.4.1.3: Store mutation for retry
    const orderItems = items.map((item) => ({
      product_id: item.product.id,
    }));
    const performMutation = async () => {
      await marketplaceService.createOrder(orderItems);
      toast.success('Order placed successfully!');
      clearCart();
      onClose();
      setMutationError(null);
      setRetryCount(0);
      lastMutationRef.current = null;
    };

    lastMutationRef.current = performMutation;
    setIsCheckingOut(true);

    try {
      await performMutation();
    } catch (error: unknown) {
      const apiError = parseApiError(error);
      setMutationError(new Error(apiError.message));
    } finally {
      setIsCheckingOut(false);
    }
  };

  // Action 3.4.1.3: Retry handler for failed mutations
  const handleRetry = async () => {
    if (!lastMutationRef.current || retryCount >= 3) return;

    setRetryCount((prev) => prev + 1);
    setIsCheckingOut(true);
    try {
      await lastMutationRef.current();
    } catch (error) {
      // Error will be handled by the mutation function
    } finally {
      setIsCheckingOut(false);
    }
  };

  return (
    <Dialog open={isOpen} onClose={onClose} title="Shopping Cart" size="lg">
      <div className="space-y-4">
        {mutationError && (
          <ErrorDisplay
            error={mutationError}
            variant="banner"
            severity="error"
            onRetry={retryCount < 3 ? handleRetry : undefined}
            context={{
              action: 'checking out',
              resource: 'cart',
            }}
            onDismiss={() => {
              setMutationError(null);
              setRetryCount(0);
              lastMutationRef.current = null;
            }}
          />
        )}
        {validationError && (
          <ErrorDisplay
            error={validationError}
            variant="inline"
            severity="error"
            size="sm"
            dismissible={false}
          />
        )}
        {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>
  );
}
