import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import dayjs from "dayjs";

import CardBox from '../../components/CardBox'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { getPageTitle } from '../../config'

import { Field, Form, Formik } from 'formik'
import FormField from '../../components/FormField'
import BaseDivider from '../../components/BaseDivider'
import BaseButtons from '../../components/BaseButtons'
import BaseButton from '../../components/BaseButton'
import FormCheckRadio from '../../components/FormCheckRadio'
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup'
import FormFilePicker from '../../components/FormFilePicker'
import FormImagePicker from '../../components/FormImagePicker'
import { SelectField } from "../../components/SelectField";
import { SelectFieldMany } from "../../components/SelectFieldMany";
import { SwitchField } from '../../components/SwitchField'
import {RichTextField} from "../../components/RichTextField";

import { update, fetch } from '../../stores/products/productsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import {saveFile} from "../../helpers/fileSaver";
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from "../../components/ImageField";

import {hasPermission} from "../../helpers/userPermissions";



const EditProducts = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    category: null,
    

    
    
    
    'product_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'sku': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'barcode': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    product_type: '',
    

    

    

    

    
    
    
    'unit_of_measure': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'tax_rate': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'default_cost': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'default_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'minimum_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    is_taxable: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    track_batch: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    track_expiry: false,
    

    

    

    

    

    

    
    
    

    

    

    
    reorder_level: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    
    product_images: [],
    

    

    
    
    

    

    

    

    

    

    
    is_active: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

    
    
    
  }
  const [initialValues, setInitialValues] = useState(initVals)

  const { products } = useAppSelector((state) => state.products)
  
  const { currentUser } = useAppSelector((state) => state.auth);
  

  const { productsId } = router.query

  useEffect(() => {
    dispatch(fetch({ id: productsId }))
  }, [productsId])

  useEffect(() => {
    if (typeof products === 'object') {
      setInitialValues(products)
    }
  }, [products])

  useEffect(() => {
      if (typeof products === 'object') {

          const newInitialVal = {...initVals};

          Object.keys(initVals).forEach(el => newInitialVal[el] = (products)[el])

          setInitialValues(newInitialVal);
      }
  }, [products])

  const handleSubmit = async (data) => {
    await dispatch(update({ id: productsId, data }))
    await router.push('/products/products-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit products')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit products'} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Category' labelFor='category'>
        <Field
            name='category'
            id='category'
            component={SelectField}
            options={initialValues.category}
            itemRef={'product_categories'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'category_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="ProductName"
    >
        <Field
            name="product_name"
            placeholder="ProductName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="SKU"
    >
        <Field
            name="sku"
            placeholder="SKU"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Barcode"
    >
        <Field
            name="barcode"
            placeholder="Barcode"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ProductType" labelFor="product_type">
        <Field name="product_type" id="product_type" component="select">
          
            <option value="stock_item">stock_item</option>
          
            <option value="service">service</option>
          
            <option value="bundle">bundle</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="UnitOfMeasure"
    >
        <Field
            name="unit_of_measure"
            placeholder="UnitOfMeasure"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TaxRate"
    >
        <Field
            type="number"
            name="tax_rate"
            placeholder="TaxRate"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DefaultCost"
    >
        <Field
            type="number"
            name="default_cost"
            placeholder="DefaultCost"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DefaultPrice"
    >
        <Field
            type="number"
            name="default_price"
            placeholder="DefaultPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="MinimumPrice"
    >
        <Field
            type="number"
            name="minimum_price"
            placeholder="MinimumPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='IsTaxable' labelFor='is_taxable'>
        <Field
            name='is_taxable'
            id='is_taxable'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='TrackBatch' labelFor='track_batch'>
        <Field
            name='track_batch'
            id='track_batch'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='TrackExpiry' labelFor='track_expiry'>
        <Field
            name='track_expiry'
            id='track_expiry'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  
    <FormField
        label="ReorderLevel"
    >
        <Field
            type="number"
            name="reorder_level"
            placeholder="ReorderLevel"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    
        <FormField>
            <Field
                label='ProductImages'
                color='info'
                icon={mdiUpload}
                path={'products/product_images'}
                name='product_images'
                id='product_images'
                schema={{
                    size: undefined,
                    formats: undefined,
                }}
                component={FormImagePicker}
            ></Field>
        </FormField>
    

  



  

  

  

  

  

  

  

  

  
    <FormField label='IsActive' labelFor='is_active'>
        <Field
            name='is_active'
            id='is_active'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='organizations' labelFor='organizations'>
        <Field
            name='organizations'
            id='organizations'
            component={SelectField}
            options={initialValues.organizations}
            itemRef={'organizations'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  


  

              <BaseDivider />
              <BaseButtons>
                <BaseButton type="submit" color="info" label="Submit" />
                <BaseButton type="reset" color="info" outline label="Reset" />
                <BaseButton type='reset' color='danger' outline label='Cancel' onClick={() => router.push('/products/products-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditProducts
