import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  addMadeDreamsCustomKitToCart,
  addMadeDreamsProductToCart,
  clearMadeDreamsCart,
  getMadeDreamsCartSummary,
  MADE_DREAMS_CART_EVENT,
  MadeDreamsCartItem,
  MadeDreamsProduct,
  readMadeDreamsCart,
  removeMadeDreamsCartItem,
  updateMadeDreamsCartQuantity,
} from '../helpers/madeDreamsCart';

export default function useMadeDreamsCart() {
  const [items, setItems] = useState<MadeDreamsCartItem[]>([]);

  const refreshCart = useCallback(() => {
    setItems(readMadeDreamsCart());
  }, []);

  useEffect(() => {
    refreshCart();

    const handleCartUpdate = () => refreshCart();

    window.addEventListener('storage', handleCartUpdate);
    window.addEventListener(MADE_DREAMS_CART_EVENT, handleCartUpdate);

    return () => {
      window.removeEventListener('storage', handleCartUpdate);
      window.removeEventListener(MADE_DREAMS_CART_EVENT, handleCartUpdate);
    };
  }, [refreshCart]);

  const addProduct = useCallback((product: MadeDreamsProduct, quantity = 1) => {
    setItems(addMadeDreamsProductToCart(product, quantity));
  }, []);

  const addCustomKit = useCallback(
    (customKit: { uploadedFileName: string; size: string; difficulty: string; price: number }) => {
      setItems(addMadeDreamsCustomKitToCart(customKit));
    },
    [],
  );

  const updateQuantity = useCallback((itemId: string, quantity: number) => {
    setItems(updateMadeDreamsCartQuantity(itemId, quantity));
  }, []);

  const removeItem = useCallback((itemId: string) => {
    setItems(removeMadeDreamsCartItem(itemId));
  }, []);

  const clearCart = useCallback(() => {
    setItems(clearMadeDreamsCart());
  }, []);

  const totals = useMemo(() => getMadeDreamsCartSummary(items), [items]);

  return {
    items,
    totals,
    addProduct,
    addCustomKit,
    updateQuantity,
    removeItem,
    clearCart,
  };
}
