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

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

// Firebase
import { getFirebaseDocs, updateFirebaseDoc } from '@vapta-systems/v2'

// Components
import { FormField, FormSelect, FormSubmit } from '@/components/Form'
import FormattedAddress from '@/components/FormattedAddress'
import Grid from '@/components/Grid'
import Label from '@/components/Label'
import Page from '@/components/Page'
import {
  Widget,
  WidgetAdmin,
  WidgetTitle,
  WidgetContent
} from '@/components/Widget'

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

export default ({ supplier: data }) => {
  const [supplier, set] = useState({})
  const [branches, setBranches] = useState([])
  const [catalogues, setCatalogues] = useState([])

  const [statistics, setStats] = useState({
    branch_count: 0,
    product_count: 0
  })

  const [edit, toggle] = useState({
    branch: null
  })

  const editBranch = id => {
    let _editing = {
      ...edit,
      branch: null
    }

    _.find(branches, b => {
      if (b.id == id) {
        return (_editing.branch = b)
      } else {
        return null
      }
    })

    toggle(_editing)
  }

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

    await updateFirebaseDoc(
      `/modules/v_procurement/suppliers/${supplier.id}/branches`,
      edit.branch.id,
      edit.branch
    )

    let _branches = _.map(branches, branch => {
      return branch.id == edit.branch.id ? (branch = edit.branch) : branch
    })

    setBranches(_branches)

    toast.success(`${edit.branch.name} has been updated`)

    return toggle(prev => ({ ...prev, branch: null }))
  }

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

    await updateFirebaseDoc(
      '/modules/v_procurement/suppliers',
      supplier.id,
      supplier
    )

    return toast.success(`${supplier.company_name} has been updated`)
  }

  useEffect(async () => {
    if (data.id) {
      set(data)
      const _branches = await getFirebaseDocs(
        `/modules/v_procurement/suppliers/${data.id}/branches`
      )
      const _products = await getFirebaseDocs('/modules/v_procurement/products')

      setStats(prev => ({ ...prev, branch_count: _branches.length }))

      _products.map(item => {
        if (item.supplier_id == data.id) {
          setStats(prev => ({
            ...prev,
            product_count: (prev.product_count += 1)
          }))
        }
      })

      setBranches(_branches)

      const _catalogues = await getFirebaseDocs(
        'modules/v_procurement/catalogues'
      )

      setCatalogues(
        _catalogues.map(catalogue => {
          return {
            name: catalogue.name,
            value: catalogue.id
          }
        })
      )
    }
  }, [data])

  if (supplier) {
    return (
      <>
        <Page
          title={supplier.company_name}
          icon='dolly'
          meta={supplier.notes}
        />

        <Grid>
          <Widget>
            <WidgetTitle icon='gear'>Modify</WidgetTitle>
            <WidgetContent>
              <form onSubmit={updateSupplier}>
                <Grid columns={1}>
                  <FormSelect
                    label='Enabled'
                    value={supplier.active}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        active: e == 'true' ? true : false
                      }))
                    }
                    options={[
                      { name: 'True', value: 'true' },
                      { name: 'False', value: 'false' }
                    ]}
                  />
                  <FormField
                    label='Company Name'
                    value={supplier.company_name}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        company_name: e
                      }))
                    }
                  />
                  <FormField
                    label='Contact First Name'
                    value={supplier.contact_first_name}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        contact_first_name: e
                      }))
                    }
                  />
                  <FormField
                    label='Contact Last Name'
                    value={supplier.contact_last_name}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        contact_last_name: e
                      }))
                    }
                  />
                  <FormField
                    label='Phone'
                    value={supplier.phone}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        phone: e
                      }))
                    }
                  />
                  <FormField
                    label='Email'
                    value={supplier.email}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        email: e
                      }))
                    }
                  />
                  <FormSelect
                    label='Catalogue'
                    value={supplier.catalogue_id}
                    onChange={e =>
                      set(prev => ({
                        ...prev,
                        catalogue_id: e
                      }))
                    }
                    options={catalogues}
                  />
                  <FormSubmit />
                </Grid>
              </form>
            </WidgetContent>
          </Widget>
          <Widget>
            <WidgetTitle icon='cart-flatbed'>
              {supplier.company_name}
            </WidgetTitle>
            <WidgetContent>
              <Grid columns={1}>
                <div>
                  <Label text='Contact' />
                  <p>
                    {supplier.contact_first_name +
                      ' ' +
                      supplier.contact_last_name}
                  </p>
                </div>
                <div>
                  <Label text='Phone' />
                  <p>{supplier.phone}</p>
                </div>
                <div>
                  <Label text='Email' />
                  <p>{supplier.email}</p>
                </div>
              </Grid>
            </WidgetContent>
          </Widget>
          <Widget>
            <WidgetTitle icon='gears'>Branch Manager</WidgetTitle>
            <WidgetContent>
              <Grid columns={1}>
                <FormSelect
                  label='Select a Branch'
                  value={edit.branch && edit.branch.name ? edit.branch.id : ''}
                  onChange={editBranch}
                  options={branches.map(branch => {
                    return {
                      name: branch.name,
                      value: branch.id
                    }
                  })}
                />
                {edit.branch && (
                  <>
                    <form onSubmit={updateBranch}>
                      <Grid columns={1}>
                        <FormField
                          label='Name'
                          value={edit.branch.name}
                          onChange={e =>
                            toggle(prev => ({
                              ...prev,
                              branch: {
                                ...prev.branch,
                                name: e
                              }
                            }))
                          }
                        />
                        <FormField
                          label='Email'
                          value={edit.branch.email}
                          onChange={e =>
                            toggle(prev => ({
                              ...prev,
                              branch: {
                                ...prev.branch,
                                email: e
                              }
                            }))
                          }
                        />
                        <FormField
                          label='Phone'
                          value={edit.branch.phone}
                          onChange={e =>
                            toggle(prev => ({
                              ...prev,
                              branch: {
                                ...prev.branch,
                                phone: e
                              }
                            }))
                          }
                        />
                        <FormField
                          label='Address 1'
                          value={edit.branch.address_1}
                          onChange={e =>
                            toggle(prev => ({
                              ...prev,
                              branch: {
                                ...prev.branch,
                                address_1: e
                              }
                            }))
                          }
                        />
                        <FormField
                          label='Address 2'
                          value={edit.branch.address_2}
                          onChange={e =>
                            toggle(prev => ({
                              ...prev,
                              branch: {
                                ...prev.branch,
                                address_2: e
                              }
                            }))
                          }
                        />
                        <FormField
                          label='Town/City'
                          value={edit.branch.town}
                          onChange={e =>
                            toggle(prev => ({
                              ...prev,
                              branch: {
                                ...prev.branch,
                                town: e
                              }
                            }))
                          }
                        />
                        <FormField
                          label='Postcode'
                          value={edit.branch.postcode}
                          onChange={e =>
                            toggle(prev => ({
                              ...prev,
                              branch: {
                                ...prev.branch,
                                postcode: e
                              }
                            }))
                          }
                        />
                        <FormSubmit />
                      </Grid>
                    </form>
                  </>
                )}
              </Grid>
            </WidgetContent>
          </Widget>
          <Widget>
            <WidgetTitle icon='map-location-dot'>Branches</WidgetTitle>
            <WidgetContent>
              <div className='flex flex-col space-y-2'>
                {branches.map(branch => (
                  <div className='border p-2 rounded'>
                    <p className='font-medium'>{branch.name}</p>
                    {branch.email && (
                      <p className='text-xs'>
                        <i className='fa-solid fa-square-envelope mr-1 text-gray-400' />
                        {branch.email}
                      </p>
                    )}
                    {branch.phone && (
                      <p className='text-xs'>
                        <i className='fa-solid fa-square-phone mr-1 text-gray-400' />
                        {branch.phone}
                      </p>
                    )}
                    <FormattedAddress data={branch} className='text-xs' />
                  </div>
                ))}
              </div>
            </WidgetContent>
          </Widget>
          <StatisticWidget
            title='Products'
            icon='box-taped'
            count={statistics.product_count}
          />
          <StatisticWidget
            title='Branches'
            icon='map-location-dot'
            count={statistics.branch_count}
          />
        </Grid>
      </>
    )
  } else return null
}
