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/batches/batchesSlice'
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";



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

    

    

    

    

    

    

    

    

    

    

    
    product: null,
    

    
    
    
    'batch_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    manufacture_start_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    manufacture_end_at: new Date(),
    

    

    

    

    

    

    

    
    
    
    'quantity_planned': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'quantity_produced': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'quantity_released': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    bmr_document: null,
    

    
    
    

    

    

    

    

    

    

    

    

    
    batch_record_files: [],
    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

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

  const { batches } = useAppSelector((state) => state.batches)
  

  const { batchesId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

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

  

  

    

  



  
    <FormField
        label="BatchNumber"
    >
        <Field
            name="batch_number"
            placeholder="BatchNumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="planned">planned</option>
          
            <option value="in_process">in_process</option>
          
            <option value="quarantined">quarantined</option>
          
            <option value="released">released</option>
          
            <option value="rejected">rejected</option>
          
            <option value="closed">closed</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="ManufactureStartAt"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.manufacture_start_at ?
                  new Date(
                      dayjs(initialValues.manufacture_start_at).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'manufacture_start_at': date})}
          />
      </FormField>
  

  

  

  

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="ManufactureEndAt"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.manufacture_end_at ?
                  new Date(
                      dayjs(initialValues.manufacture_end_at).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'manufacture_end_at': date})}
          />
      </FormField>
  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="QuantityPlanned"
    >
        <Field
            type="number"
            name="quantity_planned"
            placeholder="QuantityPlanned"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="QuantityProduced"
    >
        <Field
            type="number"
            name="quantity_produced"
            placeholder="QuantityProduced"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="QuantityReleased"
    >
        <Field
            type="number"
            name="quantity_released"
            placeholder="QuantityReleased"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='BatchRecordFiles'
            color='info'
            icon={mdiUpload}
            path={'batches/batch_record_files'}
            name='batch_record_files'
            id='batch_record_files'
            schema={{
                size: undefined,
                formats: undefined,
            }}
            component={FormFilePicker}
          ></Field>
        </FormField>
  



  

  
    <FormField label="Notes" hasTextareaHeight>
        <Field name="notes" as="textarea" placeholder="Notes" />
    </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('/batches/batches-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditBatches
