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 = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    tenant: null,
    

    
    
    
    'product_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'sku': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'barcode': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    product_status: '',
    

    

    

    

    
    
    
    'brand': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'category': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'unit': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'weight_grams': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'length_cm': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'width_cm': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'height_cm': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'cost_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'retail_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'reseller_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'agent_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'distributor_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    low_stock_threshold: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    
    product_images: [],
    

    

    
    
    

    
    short_description: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    description: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    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='Tenant' labelFor='tenant'>
        <Field
            name='tenant'
            id='tenant'
            component={SelectField}
            options={initialValues.tenant}
            itemRef={'tenants'}
      
        
      
        
      
        
      
        
      
        
            showField={'tenant_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="ProductStatus" labelFor="product_status">
        <Field name="product_status" id="product_status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="active">active</option>
          
            <option value="archived">archived</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="Brand"
    >
        <Field
            name="brand"
            placeholder="Brand"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Category"
    >
        <Field
            name="category"
            placeholder="Category"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Unit"
    >
        <Field
            name="unit"
            placeholder="Unit"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Weight(grams)"
    >
        <Field
            type="number"
            name="weight_grams"
            placeholder="Weight(grams)"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Length(cm)"
    >
        <Field
            type="number"
            name="length_cm"
            placeholder="Length(cm)"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Width(cm)"
    >
        <Field
            type="number"
            name="width_cm"
            placeholder="Width(cm)"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Height(cm)"
    >
        <Field
            type="number"
            name="height_cm"
            placeholder="Height(cm)"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="CostPrice"
    >
        <Field
            type="number"
            name="cost_price"
            placeholder="CostPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="RetailPrice"
    >
        <Field
            type="number"
            name="retail_price"
            placeholder="RetailPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="ResellerPrice"
    >
        <Field
            type="number"
            name="reseller_price"
            placeholder="ResellerPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="AgentPrice"
    >
        <Field
            type="number"
            name="agent_price"
            placeholder="AgentPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DistributorPrice"
    >
        <Field
            type="number"
            name="distributor_price"
            placeholder="DistributorPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="LowStockThreshold"
    >
        <Field
            type="number"
            name="low_stock_threshold"
            placeholder="LowStockThreshold"
        />
    </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="ShortDescription" hasTextareaHeight>
        <Field name="short_description" as="textarea" placeholder="ShortDescription" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='Description' hasTextareaHeight>
        <Field
            name='description'
            id='description'
            component={RichTextField}
        ></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
