// Hook
import { useEffect, useState } from 'react'

// Next
import { useRouter } from 'next/router'
import Link from 'next/link'

// Context
import { useAuthContext } from '@/context/auth'

import {
  // Firebase
  addFirebaseDoc,
  getFirebaseDoc,
  updateFirebaseDoc,

  // Components
  Button,
  Grid,
  Label,
  Page,
  Widget
} from '@vapta/v2-components'
import StatusBadge from '@/components/StatusBadge'

// Modules
import toast from 'react-hot-toast'

export default ({ data }) => {
  const router = useRouter()

  const { user } = useAuthContext()

  const [order, set] = useState()
  const [total, setTotal] = useState(0)
  const [admin, isAdmin] = useState(false)
  const [customer, setCustomer] = useState(null)

  const modify = async change => {
    switch (change.status) {
      case 'cancelled':
        if (process.env.NODE_ENV == 'production') {
          await addFirebaseDoc('emails', {
            to: user.email,
            message: {
              subject: 'Your order has been cancelled',
              html: ``
            }
          })

          const branch = await getFirebaseDoc(
            `modules/v_procurement/suppliers/I0yA6zFC6zCWudENMcYg/branches`,
            user.catalogue_branch
          )

          await addFirebaseDoc('emails', {
            to: branch.email,
            message: {
              subject: `Order #${order.numeric_id} cancelled`
            }
          })
        }
        toast.error('This order has been cancelled')
        break
      case 'fulfilled':
        if (process.env.NODE_ENV == 'production') {
          await addFirebaseDoc('emails', {
            to: user.email,
            message: {
              subject: 'Your order has been fulfilled',
              html: ``
            }
          })
        }
        toast.success('This order has been fulfilled')
        break
      default:
        toast('This order has been updated')
    }

    set(prev => ({ ...prev, ...change }))

    await updateFirebaseDoc('modules/v_procurement/orders', order.id, change)
  }

  const resend = async () => {
    if (process.env.NODE_ENV == 'production') {
      await addFirebaseDoc('emails', {
        to: user.email,
        message: {
          subject: 'Your order has been resent',
          html: ``
        }
      })

      const branch = await getFirebaseDoc(
        `modules/v_procurement/suppliers/I0yA6zFC6zCWudENMcYg/branches`,
        user.catalogue_branch
      )

      await addFirebaseDoc('emails', {
        to: branch.email,
        message: {
          subject: `Order #${order.numeric_id} received (resent)`
        }
      })
    }

    toast.success('This order has been resent')
  }

  useEffect(async () => {
    if (data && data.id) {
      set(data)

      if (data.items) {
        let temp = 0

        data.items.map(product => (temp += product.price * product.quantity))

        setTotal(parseFloat(temp).toFixed(2))
      }

      if (data.user_id) {
        setCustomer(await getFirebaseDoc('/users', data.user_id))
      }

      if (data.site_id) {
        setLocation(await getFirebaseDoc(`/users/${data.user_id}/sites/`, data.site_id))
      }

      isAdmin(router.pathname.startsWith('/admin'))
    }

    return () => {
      // do nothing
    }
  }, [data])

  if (order) {
    return (
      <>
        <Page title={`Order #${order.numeric_id}`} icon='file'>
          {admin && (
            <p className='bg-violet-100 flex font-medium items-center px-2 py-1 rounded text-sm text-violet-500'>
              <i className='fa-regular fa-lock mr-2' /> Admin View
            </p>
          )}
        </Page>

        <Grid>
          <div className='col-span-2 space-y-4'>
            <Widget title='Order Summary' icon='file-lines'>
              <div className='bg-gray-100 gap-x-4 grid grid-cols-6 mb-2 p-2 rounded text-xs'>
                <p className='col-span-2'>Part Number / SKU</p>
                <p className='col-span-2'>Name</p>
                <p className='text-right'>Quantity</p>
                <p className='text-right'>Price (excl VAT)</p>
              </div>
              <ul className='border flex flex-col p-2 space-y-4'>
                {order.items ? (
                  order.items.map(product => (
                    <li key={product.id} className='gap-x-4 grid grid-cols-6'>
                      <span className='col-span-2'>{product.sku}</span>
                      <span className='col-span-2'>{product.name}</span>
                      <span className='text-right'>{product.quantity}</span>
                      <span className='price text-right'>{(product.price * product.quantity).toFixed(2)}</span>
                    </li>
                  ))
                ) : (
                  <p className='text-gray-500 text-sm'>There are no items in this order.</p>
                )}
              </ul>
              <div className='bg-gray-100 gap-x-4 grid grid-cols-3 mt-2 p-2 rounded text-sm'>
                <p className='text-xs'>Total</p>
                <p />
                <p className='price text-right'>{total}</p>
              </div>
              {order.notes && (
                <div className='mt-4'>
                  <label>Additional Notes</label>
                  <p>{order.notes}</p>
                </div>
              )}
            </Widget>
          </div>
          <div className='space-y-4'>
            <Widget title='Customer' icon='file-user'>
              <Grid columns={1}>
                {customer && (
                  <div>
                    <Label text='Customer' />
                    <p>{customer.name}</p>
                    <p>{customer.email}</p>
                  </div>
                )}
                <div>
                  <Label text='Account' />
                  <p>{order.account}</p>
                </div>
                <div>
                  <Label text='Additional Information' />
                  <p>Vehicle: {order.vehicle_registration}</p>
                  <p>Technician: {order.technician_name}</p>
                  <p>Purchase Order Number: {order.po_number}</p>
                </div>
              </Grid>
            </Widget>
          </div>
          <div className='space-y-4'>
            {order.status == 'draft' && (
              <Widget title='Order in Progress' icon='clock'>
                <Grid columns={1}>
                  <p>Ready to pick up where you left off?</p>
                  <Link href={`/dashboard/order?id=${order.id}`}>
                    <a>
                      <Button>Continue Order</Button>
                    </a>
                  </Link>
                </Grid>
              </Widget>
            )}
            {order.status == 'sent' && admin && (
              <Widget title='Manage Order' icon='cog'>
                <Grid columns={1}>
                  <Button variant='action' icon='check-double' onClick={() => modify({ status: 'fulfilled' })}>
                    Fulfill this Order
                  </Button>
                  <Button icon='share' onClick={() => resend()}>
                    Resend this Order
                  </Button>
                  <Button variant='delete' icon='delete-left' onClick={() => modify({ status: 'cancelled' })}>
                    Cancel this Order
                  </Button>
                </Grid>
              </Widget>
            )}
          </div>
        </Grid>
      </>
    )
  } else return null
}
