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

import {
  generateAccountOptions,
  handleScan,
  renderCategories,
  renderProducts
} from './ECommerce.helpers'

import { ECommerceProps } from './ECommerce.types'

import './ECommerce.css'

import { BasketProductProps } from '../Basket/Basket.types'
import {
  Basket,
  Button,
  Field,
  Grid,
  Modal,
  Select,
  Widget
} from '../../components'
import { addFirebaseDoc, generateNumericId } from '../../firebase/helpers'
import { useForm, useToggle } from '../../hooks'

const ECommerce = ({
  accounts = [],
  catalogue_id,
  categories = [],
  products = [],
  user_id
}: ECommerceProps) => {
  const [category, setCategory] = useState<string | null>(null)
  const [basket, setBasket] = useState<Array<BasketProductProps>>([])

  const [details, setDetails] = useForm({})
  const [finish, toggleFinish] = useToggle(false)

  const [success, toggleSuccess] = useToggle(false)

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [_, setScan] = useState<string>('')

  const handleOrder = async (status: string) => {
    const _order = {
      account: details.account ?? null,
      items: basket,
      notes: details.notes ?? null,
      numeric_id: await generateNumericId(
        '/modules/v_procurement/orders',
        'numeric_id'
      ),
      po_number: details.po_number,
      status: status,
      technician_name: details.technician_name,
      user_id: user_id,
      vehicle_registration: details.registration_number
    }

    await addFirebaseDoc('/modules/v_procurement/orders', _order)

    setTimeout(() => {
      // Close Modal
      toggleFinish(false)

      setBasket([])

      setDetails({
        account: '',
        notes: '',
        po_number: '',
        technician_name: '',
        vehicle_registration: ''
      })
    }, 500)
  }

  const listener = (event: KeyboardEvent) => {
    if (event.key.length === 1) {
      setScan(state => (state += event.key))
    }

    if (event.key === 'Enter') {
      return handleScan(setBasket, setScan)
    }
  }

  useEffect(() => {
    window.addEventListener('keydown', listener)

    return () => window.removeEventListener('keydown', listener)
  }, [])

  // Auto close Success Modal
  useEffect(() => {
    if (success) {
      setTimeout(() => {
        toggleSuccess(false)
      }, 5000) // After 5 seconds
    }
  }, [success])

  return (
    <>
      <Grid columns={5}>
        <div className='col-span-3 space-y-4'>
          <Widget title='Products' icon='asterisk'>
            {!category ? (
              renderCategories(categories, setCategory)
            ) : (
              <p
                className='cursor-pointer text-gray-500 hover:text-black'
                onClick={() => setCategory(null)}
              >
                <i className='fa-regular fa-long-arrow-left mr-2' />
                Return to Categories
              </p>
            )}
            {renderProducts(products, category, catalogue_id, setBasket)}
          </Widget>
        </div>
        <div className='col-span-2 space-y-4'>
          {basket.length > 0 && (
            <Widget title='Finish Order' icon='check-circle'>
              <Grid columns={2}>
                <Button>Save for Later</Button>
                <Button variant='action' onClick={toggleFinish}>
                  Submit Order
                </Button>
              </Grid>
            </Widget>
          )}
          <Widget title='Basket' icon='basket-shopping'>
            <Basket data={basket} />
          </Widget>
        </div>
      </Grid>
      <Modal title='Final Details' close={toggleFinish} visible={finish}>
        <Grid columns={2}>
          <Field
            type='text'
            label='Technician Name'
            value={details.technician_name}
            onChange={(value: string) => setDetails({ technician_name: value })}
          />
          <Field
            type='text'
            label='Registration Number'
            value={details.registration_number}
            onChange={(value: string) =>
              setDetails({ registration_number: value })
            }
          />
          <Field
            type='text'
            label='Notes'
            value={details.notes}
            onChange={(value: string) => setDetails({ notes: value })}
          />
          <Field
            type='text'
            label='PO Number'
            value={details.po_number}
            onChange={(value: string) => setDetails({ po_number: value })}
          />
          <Select
            label='Account'
            value={details.account}
            onChange={(value: string) => setDetails({ account: value })}
            options={generateAccountOptions(accounts)}
          />
          <span className='col-span-2 flex items-center justify-center'>
            <Button variant='action' onClick={() => handleOrder('pending')}>
              Place my Order
            </Button>
          </span>
        </Grid>
      </Modal>
      <Modal
        title='Order Complete'
        icon='check-circle'
        visible={success}
        close={toggleSuccess}
      >
        <p>Your order was placed successfully!</p>
      </Modal>
    </>
  )
}

export default ECommerce
