import { Checkbox, Spinner } from '@chakra-ui/react'
import React, { useState } from 'react'

import { getAuth } from '~/libs/auth'
import { CartItem } from '~/types/cart'
import { upsertUserCart } from '~/services/cart'

import { useCartStore } from '../stores/useCartStore'

type Props = {
  item: CartItem
}

const CartItemSelect = ({ item }: Props) => {
  const auth = getAuth()
  const { updateCartItem, cart } = useCartStore()

  const [isLoad, setIsLoad] = useState<boolean>(false)

  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (typeof auth !== 'object' || !cart) return
    
    setIsLoad(true);
    const updatedCartItems = cart.products.map(cartItem =>
      cartItem.id === item.id
        ? { ...cartItem, selected: e.target.checked }
        : cartItem
    );

    // Update the entire cart
    const updatedCart = { ...cart, products: updatedCartItems };
    updateCartItem(updatedCart);

    setIsLoad(false);
  }

  return (
    <div className='w-6 my-auto'>
      {isLoad && (
        <Spinner className='my-auto' size='sm' />
      )}

      {!isLoad && (
        <Checkbox
          borderColor='gray.600'
          colorScheme='red'
          size='lg'
          isChecked={item.selected}
          onChange={handleChange}
        />
      )}
    </div>
  )
}

export default CartItemSelect