import React, { useEffect, useState } from 'react'

import { BasketProps, BasketProductProps } from './Basket.types'

import { handleQuantity } from './Basket.helpers'

import './Basket.css'

import { Grid } from '../../components'

const Basket = ({ data = [], setData }: BasketProps) => {
  const [total, set] = useState(0)

  useEffect(() => {
    if (data.length > 0) {
      let _total = 0

      data.forEach(item => (_total += item.unit_price * item.quantity))

      set(_total)
    }
  }, [data])

  return (
    <Grid columns={1}>
      <Grid columns={4} className='bg-gray-100 p-1 rounded text-xs'>
        <p className='col-span-2'>Name</p>
        <p className='text-right'>Quantity</p>
        <p className='text-right'>Price</p>
      </Grid>

      <div className='flex flex-col max-h-64 overflow-y-auto space-y-4'>
        {data.length > 0 ? (
          data
            .map((item: BasketProductProps) => (
              <Grid columns={4}>
                <p className='col-span-2'>
                  <span>{item.name}</span>
                  <span className='block text-gray-400 text-xs'>
                    SKU: {item.sku}
                  </span>
                </p>
                <p className='flex items-center justify-between space-x-2'>
                  <button onClick={() => handleQuantity(item.sku, -1, setData)}>
                    <i className='fa-regular fa-minus-circle fa-lg text-red-500' />
                  </button>
                  {item.quantity}
                  <button onClick={() => handleQuantity(item.sku, 1, setData)}>
                    <i className='fa-regular fa-plus-circle fa-lg text-green-500' />
                  </button>
                </p>
                <p className='text-right'>
                  £{(item.unit_price * item.quantity).toFixed(2)}
                </p>
              </Grid>
            ))
            .reverse()
        ) : (
          <p>Add items to your basket</p>
        )}
      </div>

      <Grid columns={4} className='bg-gray-100 p-1 rounded text-xs'>
        <p className='col-span-3'>Total (excl. VAT)</p>
        <p className='text-right'>£{total.toFixed(2)}</p>
      </Grid>
    </Grid>
  )
}

export default Basket
