import { Checkbox, Spinner } from '@chakra-ui/react'
import React, { useState, useEffect } 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
  itemSelected?: boolean
}

const CartItemSelect = ({ item, itemSelected }: Props) => {
  const auth = getAuth()
  const { loadCart } = useCartStore()

  const [isLoad, setIsLoad] = useState<boolean>(false)
  const [isChecked, setIsChecked] = useState<boolean>(itemSelected ?? true)

  const handleChange = async (isChecked: boolean) => {
    if (typeof auth !== 'object') return

    setIsLoad(true)
    await upsertUserCart({
      userId: auth.id,
      type: item.cart_type,
      id: item.id,
      qty: item.quantity,
      selected: isChecked,
    })
    await loadCart(auth.id)
    setIsLoad(false)
  }

  useEffect(() => {
    if (typeof itemSelected === 'boolean') {
      setIsChecked(itemSelected)
      handleChange(itemSelected)
    }
  }, [itemSelected])

  const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { checked } = e.target
    setIsChecked(checked)
    handleChange(checked)
  }

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

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

export default CartItemSelect
