import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import { useRouter } from 'next/router'
import React, { ReactElement, useEffect, useState } from 'react'
import { Form, Formik } from 'formik'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import ProductSkuFormContent from '../../components/Products/ProductSkuFormContent'
import { getPageTitle } from '../../config'
import { fetch, update } from '../../stores/products/productsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'

const initVals = {
  sku: '',
  product_name: '',
  brand: '',
  category: null,
  short_description: '',
  long_description: '',
  images: [],
  spec_sheet: [],
  pack_size: '',
  units_per_case: '',
  unit_weight_lbs: '',
  case_weight_lbs: '',
  uom: '',
  moq_cases: '',
  temperature_zone: 'ambient',
  product_status: 'active',
  allergens: '',
  certifications: '',
  is_sample_eligible: false,
}

const EditProductsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const [initialValues, setInitialValues] = useState(initVals)
  const { products } = useAppSelector((state) => state.products)
  const { id } = router.query
  const productId = Array.isArray(id) ? id[0] : id

  useEffect(() => {
    if (!productId) {
      return
    }

    dispatch(fetch({ id: productId }))
  }, [dispatch, productId])

  useEffect(() => {
    if (!products || typeof products !== 'object' || Array.isArray(products)) {
      return
    }

    const newInitialVal: any = { ...initVals }
    Object.keys(initVals).forEach((key) => {
      newInitialVal[key] = products[key] ?? initVals[key]
    })
    setInitialValues(newInitialVal)
  }, [products])

  const handleSubmit = async (data) => {
    if (!productId) {
      throw new Error('Product id is required to update a contract SKU')
    }

    await dispatch(update({ id: productId, data }))
    await router.push('/products/products-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit contract SKU')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Edit contract SKU'
          main
        >
          {''}
        </SectionTitleLineWithButton>

        <Formik
          enableReinitialize
          initialValues={initialValues}
          onSubmit={(values) => handleSubmit(values)}
        >
          <Form>
            <ProductSkuFormContent mode='edit' categoryValue={initialValues.category} />
          </Form>
        </Formik>
      </SectionMain>
    </>
  )
}

EditProductsPage.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission='UPDATE_PRODUCTS'>
      {page}
    </LayoutAuthenticated>
  )
}

export default EditProductsPage
