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

// Next
import Image from 'next/image'
import { useRouter } from 'next/router'

// Firebase
import {
  addStorageItem,
  getFirebaseDocs,
  updateFirebaseDoc,
  deleteFirebaseDoc
} from '@vapta-systems/v2'
import { orderBy } from 'firebase/firestore'

// Components
import Button from '@/components/Button'
import { FormField, FormSelect, FormSubmit } from '@/components/Form'
import Grid from '@/components/Grid'
import Page from '@/components/Page'
import Modal from '@/components/Modal'
import StatisticWidget from '@/components/StatisticWidget'
import { Widget, WidgetTitle, WidgetContent } from '@/components/Widget'

// Modules
import _ from 'lodash'
import { toast } from 'react-hot-toast'

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

  const [product, set] = useState({})

  const [catalogues, setCatalogues] = useState([])
  const [categories, setCategories] = useState([])
  const [suppliers, setSuppliers] = useState([])

  const [deletePopup, toggleDeletePopup] = useState(false)
  const [deleteConfirmation, setDeleteConfirmation] = useState('')

  const thumbnail = useRef(null)

  const deleteProduct = async () => {
    await deleteFirebaseDoc('modules/v_procurement/products', product.id)

    toast.success(`${product.name} has been deleted`)

    return router.back()
  }

  const updateProduct = async event => {
    event.preventDefault()

    await updateFirebaseDoc(
      '/modules/v_procurement/products',
      product.id,
      product
    )

    return toast.success(`${product.name} has been updated`)
  }

  const updateThumbnail = async event => {
    event.preventDefault()

    addStorageItem(
      `/modules/v_procurement/product-images/`,
      event.target.files[0],
      product.id
    ).then(async url => {
      await updateFirebaseDoc('/modules/v_procurement/products', product.id, {
        thumbnail: url
      })

      set(prev => ({ ...prev, thumbnail: url }))

      return toast.success(`${product.name} has a fancy new image`)
    })
  }

  useEffect(async () => {
    if (data) {
      set(data)

      setCatalogues(await getFirebaseDocs('modules/v_procurement/catalogues'))
      setCategories(
        await getFirebaseDocs(
          'modules/v_procurement/categories',
          orderBy('name', 'asc')
        )
      )
      setSuppliers(await getFirebaseDocs('modules/v_procurement/suppliers'))
    }
  }, [data])

  return (
    <>
      <Page title={product.name} icon='shopping-bag' meta={product.desc}>
        <Button icon='delete-left' onClick={() => toggleDeletePopup(true)}>
          Delete
        </Button>
      </Page>

      <Grid>
        <Widget className='col-span-2'>
          <WidgetTitle icon='unlock'>Product Manager</WidgetTitle>
          <WidgetContent>
            <form onSubmit={updateProduct}>
              <Grid columns={2}>
                <FormSelect
                  label='Available'
                  tooltip='Toggle if this item appears in the catalogue'
                  value={product.available}
                  onChange={e =>
                    set(prev => ({
                      ...prev,
                      available: e == 'true' ? true : false
                    }))
                  }
                  options={[
                    { name: 'True', value: 'true' },
                    { name: 'False', value: 'false' }
                  ]}
                />
                <FormField
                  label='Name'
                  value={product.name}
                  onChange={e => set(prev => ({ ...prev, name: e }))}
                />
                <FormField
                  label='SKU'
                  tooltip='This has to be unique'
                  value={product.sku}
                  onChange={e => set(prev => ({ ...prev, sku: e }))}
                />
                <FormField
                  label='OE Number'
                  tooltip='Original Equipment Number'
                  value={product.oe_number}
                  onChange={e => set(prev => ({ ...prev, oe_number: e }))}
                />
                <FormField
                  label='Price'
                  type='number'
                  value={product.unit_price}
                  onChange={e =>
                    set(prev => ({ ...prev, unit_price: parseFloat(e) }))
                  }
                />
                <FormField
                  label='Sale Price'
                  type='number'
                  value={product.sale_price}
                  onChange={e =>
                    set(prev => ({ ...prev, sale_price: parseFloat(e) }))
                  }
                />
                <FormField
                  label='Description'
                  value={product.desc}
                  onChange={e => set(prev => ({ ...prev, desc: e }))}
                />
                <FormField
                  label='Stock'
                  type='number'
                  value={product.in_stock}
                  onChange={e => set(prev => ({ ...prev, in_stock: e }))}
                />
                <FormField
                  label='Items per Unit'
                  tooltip='How many are items are in this product?'
                  type='number'
                  value={product.quantity_per_unit}
                  onChange={e =>
                    set(prev => ({ ...prev, quantity_per_unit: e }))
                  }
                />
                <FormField
                  label='Re-order Level'
                  tooltip='Number of stock before re-ordering'
                  type='number'
                  value={product.reorder_level}
                  onChange={e => set(prev => ({ ...prev, reorder_level: e }))}
                />
                <FormField
                  label='Re-order Quantity'
                  tooltip='How much stock to re-order'
                  type='number'
                  value={product.reorder_quantity}
                  onChange={e =>
                    set(prev => ({ ...prev, reorder_quantity: e }))
                  }
                />

                <div>
                  <label>Category</label>
                  <select
                    value={product.category_id}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        category_id: e.target.value
                      }))
                    }
                  >
                    <option hidden>Select a Category</option>
                    {categories.map(category => (
                      <option key={category.id} value={category.id}>
                        {category.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label>Catalogue</label>
                  <select
                    value={product.catalogue_id}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        catalogue_id: e.target.value
                      }))
                    }
                  >
                    <option hidden>Select a Category</option>
                    {catalogues.map(catalogue => (
                      <option key={catalogue.id} value={catalogue.id}>
                        {catalogue.name}
                      </option>
                    ))}
                  </select>
                </div>
                <span className='bg-gray-100 col-span-full font-medium p-2 rounded text-gray-500 text-xs'>
                  Supplier Manager
                </span>
                <Grid columns={3} className='col-span-full'>
                  <FormSelect
                    label='Supplier'
                    value={product.supplier_id}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        supplier_id: e
                      }))
                    }
                    options={suppliers}
                  />
                  <FormField
                    label='Part Reference'
                    value={product.supplier_reference}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        supplier_reference: e
                      }))
                    }
                  />
                  <FormField
                    label='Part Cost'
                    icon='sterling-sign'
                    value={product.supplier_cost}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        supplier_cost: parseFloat(e).toFixed(2)
                      }))
                    }
                  />
                  <FormSelect
                    label='Supplier 2'
                    value={product.supplier_id_2}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        supplier_id: e
                      }))
                    }
                    options={suppliers}
                  />
                  <FormField
                    label='Part Reference'
                    value={product.supplier_reference_2}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        supplier_reference: e
                      }))
                    }
                  />
                  <FormField
                    label='Part Cost'
                    icon='sterling-sign'
                    value={product.supplier_cost_2}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        supplier_cost: parseFloat(e).toFixed(2)
                      }))
                    }
                  />
                  <FormSelect
                    label='Supplier 3'
                    value={product.supplier_id_3}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        supplier_id: e
                      }))
                    }
                    options={suppliers}
                  />
                  <FormField
                    label='Part Reference'
                    value={product.supplier_reference_3}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        supplier_reference: e
                      }))
                    }
                  />
                  <FormField
                    label='Part Cost'
                    icon='sterling-sign'
                    value={product.supplier_cost_3}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        supplier_cost: parseFloat(e).toFixed(2)
                      }))
                    }
                  />
                </Grid>
                <FormSubmit />
              </Grid>
            </form>
          </WidgetContent>
        </Widget>
        <Widget>
          <WidgetTitle icon='info'>Product</WidgetTitle>
          <WidgetContent>
            <div className='flex flex-row space-4'>
              <div className='bg-gray-200 block group h-36 mr-4 relative rounded w-36'>
                <input
                  type='file'
                  className='hidden'
                  ref={thumbnail}
                  onChange={updateThumbnail}
                />
                <Image
                  src={`https://cdn.vapta.co.uk/product_images/${product.sku}.jpg`}
                  layout='fill'
                  objectFit='cover'
                  className='group-hover:hidden rounded'
                />
                <div
                  className='absolute bg-gray-500 bg-opacity-75 cursor-pointer h-36 hidden group-hover:flex items-center justify-center left-0 rounded top-0 w-full'
                  onClick={() => thumbnail.current.click()}
                >
                  <i className='fa-regular fa-upload text-white text-2xl' />
                </div>
              </div>
              <div>
                <p className='flex font-medium items-center mb-2'>
                  {product.name}
                </p>
                <p className='text-gray-500 text-xs'>SKU: {product.sku}</p>
                <p className={`my-2 price ${product.sale_price && 'sale'}`}>
                  {product.unit_price}
                  {product.sale_price > 0 && (
                    <span className='sale_price'>
                      {product.sale_price ?? ''}
                    </span>
                  )}
                </p>
                <span className='text-gray-500 text-sm'>Description</span>
                <p>{product.desc}</p>
              </div>
            </div>
          </WidgetContent>
        </Widget>
        <StatisticWidget
          icon='box-taped'
          title='In Stock'
          count={product.in_stock}
        />
      </Grid>
      <Modal
        title='Are you sure?'
        icon='trash-xmark'
        visible={deletePopup}
        close={() => toggleDeletePopup(false)}
        width='w-2/5'
      >
        You are going to delete <b>{product.name}</b>, are you sure you want to
        proceed?
        <FormField
          label={`Please type ${product.name} to proceed`}
          value={deleteConfirmation}
          onChange={e => setDeleteConfirmation(e)}
          className='my-4'
        />
        <Button
          variant='delete'
          icon='trash-xmark'
          onClick={() => deleteProduct()}
          disabled={deleteConfirmation !== product.name}
          className='mx-auto'
        >
          Confirm Delete
        </Button>
      </Modal>
    </>
  )
}
