import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import toast from 'react-hot-toast';
import { showCartToast } from '../components/CartToast';

export interface CartItem {
  variantId: number;
  productId: number;
  productName: string;
  productSlug: string;
  brandName: string;
  volume: string;
  price: number;
  quantity: number;
  image: string;
  voucherId?: number;
  productType?: string;
}

interface CartContextType {
  items: CartItem[];
  addItem: (item: Omit<CartItem, 'quantity'>, options?: { silent?: boolean }) => Promise<void>;
  removeItem: (variantId: number) => Promise<void>;
  updateQuantity: (variantId: number, quantity: number) => Promise<void>;
  clearCart: () => Promise<void>;
  refreshCart: () => Promise<void>;
  getTotalPrice: () => number;
  getTotalItems: () => number;
  isLoading: boolean;
}

const CartContext = createContext<CartContextType | undefined>(undefined);

export const CartProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [items, setItems] = useState<CartItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const refreshCart = async () => {
    try {
      const response = await fetch('/api/cart');
      if (response.ok) {
        const data = await response.json();
        setItems(data.items || []);
      }
    } catch (error) {
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    void refreshCart();
  }, []);

  const addItem = async (newItem: Omit<CartItem, 'quantity'>, options?: { silent?: boolean }) => {
    try {
      const existingItem = items.find((item) => item.variantId === newItem.variantId);

      const response = await fetch('/api/cart', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...newItem,
          quantity: 1,
        }),
      });

      if (response.ok) {
        const cartResponse = await fetch('/api/cart');
        if (cartResponse.ok) {
          const data = await cartResponse.json();
          setItems(data.items || []);
        }

        if (!options?.silent) {
          showCartToast(existingItem ? 'increase' : 'add', newItem);
        }
      } else {
        const errorData = await response.json();
        const errorMessage = errorData.error || 'Chyba při přidávání do košíku';
        toast.error(errorMessage);
      }
    } catch (error) {
      toast.error('Chyba při přidávání do košíku');
    }
  };

  const removeItem = async (variantId: number) => {
    try {
      const removedItem = items.find((item) => item.variantId === variantId);

      const response = await fetch('/api/cart', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ variantId }),
      });

      if (response.ok) {
        const cartResponse = await fetch('/api/cart');
        if (cartResponse.ok) {
          const data = await cartResponse.json();
          setItems(data.items || []);
        }

        if (removedItem) {
          const restoredItem: Omit<CartItem, 'quantity'> = {
            variantId: removedItem.variantId,
            productId: removedItem.productId,
            productName: removedItem.productName,
            productSlug: removedItem.productSlug,
            brandName: removedItem.brandName,
            volume: removedItem.volume,
            price: removedItem.price,
            image: removedItem.image,
            voucherId: removedItem.voucherId,
            productType: removedItem.productType,
          };
          showCartToast('remove', restoredItem, () => {
            void addItem(restoredItem, { silent: true });
          });
        }
      }
    } catch (error) {
      toast.error('Chyba při odebírání z košíku');
    }
  };

  const updateQuantity = async (variantId: number, quantity: number) => {
    try {
      if (quantity <= 0) {
        removeItem(variantId);
        return;
      }

      const response = await fetch('/api/cart', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ variantId, quantity }),
      });

      if (response.ok) {
        const cartResponse = await fetch('/api/cart');
        if (cartResponse.ok) {
          const data = await cartResponse.json();
          setItems(data.items || []);
        }
      } else {
        const errorData = await response.json();
        const errorMessage = errorData.error || 'Chyba při aktualizaci množství';
        toast.error(errorMessage);
      }
    } catch (error) {
      toast.error('Chyba při aktualizaci množství');
    }
  };

  const clearCart = async () => {
    try {
      // Odstraníme všechny položky
      for (const item of items) {
        await fetch('/api/cart', {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ variantId: item.variantId }),
        });
      }
      setItems([]);
    } catch (error) {
      toast.error('Chyba při mazání košíku');
    }
  };

  const getTotalPrice = (): number => {
    return items.reduce((total, item) => total + item.price * item.quantity, 0);
  };

  const getTotalItems = (): number => {
    return items.reduce((total, item) => total + item.quantity, 0);
  };

  const value: CartContextType = {
    items,
    addItem,
    removeItem,
    updateQuantity,
    clearCart,
    refreshCart,
    getTotalPrice,
    getTotalItems,
    isLoading,
  };

  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
};

export const useCart = () => {
  const context = useContext(CartContext);
  if (!context) {
    throw new Error('useCart must be used within CartProvider');
  }
  return context;
};
