import React from 'react'
import { Box, Flex, Button, Divider, HStack, Text } from '@chakra-ui/react'
import { formatCurrency } from '../utils/functions.js'
import { FiTrash2 } from 'react-icons/fi'
import { HiOutlineLocationMarker } from 'react-icons/hi'
import { useEvaluate } from '@qorebase/app-component'

const url = 'https://staging-qore-data-hair-353194.qore.dev'
const headers = {
  accept: '*/*',
  'x-qore-engine-admin-secret': 'cBfO0PFdM65CfHTknZT5oYxf3y9G4JCW',
}

function Item(props: any) {
  const {
    item,
    setAllSubtotal,
    setRows,
    setOnLoadProcess,
    onLoadProcess,
  } = props

  const title = useEvaluate(props.properties.title)
  const price = useEvaluate(props.properties.price)
  const location = useEvaluate(props.properties.location)
  const date = useEvaluate(props.properties.date)

  const [qty, setQty] = React.useState(item.qty)

  const client = props.hooks.useClient()

  const increment = async () => {
    try {
      setOnLoadProcess(true)
      //get cart by id
      const response = await client.project.axios({
        method: 'post',
        headers,
        url: `${url}/v1/execute`,
        data: {
          operations: [
            {
              operation: 'Select',
              instruction: {
                table: 'order_history',
                name: 'data',
                condition: {
                  cart_id_items: item.id,
                },
              },
            },
          ],
        },
      })

      if (!response.data.results.data.length) {
        throw new Error('Cart tidak ditemukan!')
      }

      const cart = response.data.results.data[0]

      //update cart summary, and update cart item
      await client.project.axios({
        method: 'post',
        headers,
        url: `${url}/v1/execute`,
        data: {
          operations: [
            {
              operation: 'Update',
              instruction: {
                table: 'order_history',
                name: 'UpdateCart',
                condition: {
                  id: cart.id,
                },
                set: {
                  total_price: Number(cart.total_price) + Number(item.price),
                },
              },
            },
            {
              operation: 'Update',
              instruction: {
                table: 'cart',
                name: 'UpdateCartItem',
                condition: {
                  id: item.id,
                },
                set: {
                  qty: qty + 1,
                },
              },
            },
          ],
        },
      })
      setAllSubtotal(Number(cart.total_price) + Number(item.price))
      setQty(qty + 1)

      setOnLoadProcess(false)
    } catch (error) {
      throw new Error(error)
    }
  }

  const decrement = async () => {
    try {
      //get cart by id
      setOnLoadProcess(true)

      const response = await client.project.axios({
        method: 'post',
        headers,
        url: `${url}/v1/execute`,
        data: {
          operations: [
            {
              operation: 'Select',
              instruction: {
                table: 'order_history',
                name: 'data',
                condition: {
                  cart_id_items: item.id,
                },
              },
            },
          ],
        },
      })

      if (!response.data.results.data.length) {
        throw new Error('Cart tidak ditemukan!')
      }

      const cart = response.data.results.data[0]

      //update cart summary, and update cart item
      await client.project.axios({
        method: 'post',
        headers,
        url: `${url}/v1/execute`,
        data: {
          operations: [
            {
              operation: 'Update',
              instruction: {
                table: 'order_history',
                name: 'UpdateCart',
                condition: {
                  id: cart.id,
                },
                set: {
                  total_price: Number(cart.total_price) - Number(item.price),
                },
              },
            },
            {
              operation: 'Update',
              instruction: {
                table: 'cart',
                name: 'UpdateCartItem',
                condition: {
                  id: item.id,
                },
                set: {
                  qty: qty - 1,
                },
              },
            },
          ],
        },
      })

      setAllSubtotal(Number(cart.total_price) - Number(item.price))
      setQty(qty - 1)

      setOnLoadProcess(false)
    } catch (error) {
      throw new Error(error)
    }
  }

  const remove = async () => {
    try {
      setOnLoadProcess(true)
      //get cart by id
      const response = await client.project.axios({
        method: 'post',
        headers,
        url: `${url}/v1/execute`,
        data: {
          operations: [
            {
              operation: 'Select',
              instruction: {
                table: 'order_history',
                name: 'data',
                condition: {
                  cart_id_items: item.id,
                },
              },
            },
          ],
        },
      })

      if (!response.data.results.data.length) {
        throw new Error('Cart tidak ditemukan!')
      }

      const cart = response.data.results.data[0]

      //update cart summary, and remove cart item
      await client.project.axios({
        method: 'post',
        headers,
        url: `${url}/v1/execute`,
        data: {
          operations: [
            {
              operation: 'Update',
              instruction: {
                table: 'order_history',
                name: 'UpdateCart',
                condition: {
                  id: cart.id,
                },
                set: {
                  total_price:
                    Number(cart.total_price) - Number(item.price) * qty,
                },
              },
            },
            {
              operation: 'Delete',
              instruction: {
                table: 'cart',
                name: 'DeleteCartItem',
                condition: {
                  id: item.id,
                },
              },
            },
          ],
        },
      })

      const cartResp = await client.project.axios({
        method: 'post',
        headers,
        url: `${url}/v1/execute`,
        data: {
          operations: [
            {
              operation: 'Select',
              instruction: {
                table: 'cart',
                name: 'data',
                condition: {
                  cart_id: cart.id,
                },
              },
            },
          ],
        },
      })

      setRows(cartResp.data.results.data)

      setAllSubtotal(Number(cart.total_price) - Number(item.price) * qty)
      setQty(0)

      setOnLoadProcess(false)
    } catch (error) {
      throw new Error(error)
    }
  }

  if (qty <= 0) return null
  return (
    <Box
      borderColor={{ base: 'gray.200', md: 'none' }}
      key={item.id}
      bg={item?.isReachMaxedQuota ? "#E7e7e7" : "#FFFFFF"}
      borderRadius="4px"
      boxShadow={'lg'}
    >
      <Box flex={1} flexDirection="column" p={2}>
        <Flex alignItems={'start'}>
          <Box
            flex={1}
            flexDirection="row"
            p={2}
            justifyContent={'space-between'}
          >
            <Box flexDir={'column'} display={'flex'}>
              <Text fontSize="sm" noOfLines={2} fontWeight="bold">
                {
                  item?.isReachMaxedQuota ? (
                    <Box>
                      {title} - This Class has Reach Maxed Quota
                    </Box>
                  ) : (
                    <Box>
                      {title}
                    </Box>
                  )
                }
              </Text>
              <Text fontSize="sm" fontWeight="bold" color="#EE7105">
                {formatCurrency(price)} x {qty}
              </Text>
              <Text fontSize={'12px'} color={'#A2A2A2'} noOfLines={1}>
                {date}
              </Text>
            </Box>
          </Box>

          <Box p={2}>
            <Button
              _hover={{
                color: '#fff',
                backgroundColor: '#480F6A',
                border: '1px',
              }}
              size={'sm'}
              backgroundColor={'white'}
              color={'#747474'}
              onClick={remove}
              isDisabled={onLoadProcess}
            >
              <FiTrash2 />
            </Button>
          </Box>
        </Flex>
        <Divider color={'#F5F5F5'} px={2}></Divider>

        <Box
          flex={1}
          flexDirection="column"
          justifyContent={'space-between'}
          alignItems={'center'}
          px={2}
        >
          <Flex mt={2} justifyContent={'space-between'} alignItems={'center'}>
            <Box display={'flex'} alignItems={'center'} flexDirection={'row'}>
              <HiOutlineLocationMarker size={'12px'} color={'#A2A2A2'} />
              <Text fontSize="12px" color={'#A2A2A2'} marginLeft={'5px'}>
                {location}
              </Text>
            </Box>
            <HStack>
              <Button
                _hover={{
                  color: '#fff',
                  backgroundColor: '#480F6A',
                  border: '1px',
                }}
                size={'sm'}
                backgroundColor={'white'}
                color={'#171717'}
                onClick={decrement}
                isDisabled={qty == 1 || onLoadProcess || qty == 1}
              >
                -
              </Button>
              <Text
                size={'sm'}
                textAlign={'center'}
                width={'40px'}
                color={'#171717'}
              >
                {qty}
              </Text>
              <Button
                _hover={{
                  color: '#fff',
                  backgroundColor: '#480F6A',
                  border: '1px',
                }}
                size={'sm'}
                backgroundColor={'white'}
                color={'#171717'}
                onClick={increment}
                isDisabled={
                  item.quantity == qty ||
                  onLoadProcess ||
                  qty >= item.max_quota - item.current_quota
                }
              >
                +
              </Button>
            </HStack>
          </Flex>
        </Box>
      </Box>
    </Box>
  )
}
export default Item
