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

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

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

export default ({ category: data }) => {
  const [category, set] = useState({})

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

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

    await updateFirebaseDoc(
      '/modules/v_procurement/categories',
      router.query.id,
      category
    )

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

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

      const _products = await getFirebaseDocs('/modules/v_procurement/products')

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

  return (
    <>
      <Page title={category.name} icon='bookmark' meta={category.desc} />

      <Grid>
        <Widget>
          <WidgetTitle icon='bookmark'>{category.name}</WidgetTitle>
          <WidgetContent>{category.desc}</WidgetContent>
          <WidgetAdmin>
            <form onSubmit={updateCategory}>
              <Grid columns={1}>
                <FormSelect
                  label='Available'
                  value={category.active}
                  onChange={e =>
                    set(prev => ({
                      ...prev,
                      active: e == 'true' ? true : false
                    }))
                  }
                  options={[
                    { name: 'True', value: 'true' },
                    { name: 'False', value: 'false' }
                  ]}
                />
                <FormField
                  label='Name'
                  value={category.name}
                  onChange={e =>
                    set(prev => ({
                      ...prev,
                      name: e
                    }))
                  }
                />
                <FormField
                  label='Description'
                  value={category.desc}
                  onChange={e =>
                    set(prev => ({
                      ...prev,
                      desc: e
                    }))
                  }
                />
                <FormSubmit />
              </Grid>
            </form>
          </WidgetAdmin>
        </Widget>
        <StatisticWidget title='Products' count={statistics.product_count} />
      </Grid>
    </>
  )
}
