import { useState, useCallback } from 'react';

export interface CheckoutItem {
  id: string;
  name: string;
  price: string;
  quantity: number;
}

export const useCheckout = () => {
  const [items, setItems] = useState<CheckoutItem[]>([]);
  const [isProcessing, setIsProcessing] = useState(false);

  const addItem = useCallback((item: CheckoutItem) => {
    setItems(prev => {
      const existing = prev.find(i => i.id === item.id);
      if (existing) {
        return prev.map(i => i.id === item.id ? { ...i, quantity: i.quantity + item.quantity } : i);
      }
      return [...prev, item];
    });
  }, []);

  const removeItem = useCallback((id: string) => {
    setItems(prev => prev.filter(i => i.id !== id));
  }, []);

  const updateQuantity = useCallback((id: string, quantity: number) => {
    if (quantity <= 0) {
      removeItem(id);
      return;
    }
    setItems(prev => prev.map(i => i.id === id ? { ...i, quantity } : i));
  }, [removeItem]);

  const processCheckout = useCallback(async () => {
    setIsProcessing(true);
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 2000));
      setItems([]);
      return { success: true };
    } catch (error) {
      return { success: false, error };
    } finally {
      setIsProcessing(false);
    }
  }, []);

  const total = items.reduce((sum, item) => {
    const price = parseFloat(item.price.replace(/[^0-9.-]+/g, ''));
    return sum + (price * item.quantity);
  }, 0);

  return {
    items,
    addItem,
    removeItem,
    updateQuantity,
    processCheckout,
    total,
    isProcessing,
  };
};
