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/inspections/inspectionsSlice'
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 EditInspectionsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    
    'inspection_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    inspection_type: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    inspection_plan: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    material: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    lot: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    production_order: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    work_order_operation: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    inspector_user: null,
    

    
    
    

    

    

    

    

    
    started_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    completed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    result: '',
    

    

    

    

    
    
    
    'sample_size': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    summary: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    evidence_files: [],
    

    

    

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

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

  const { id } = router.query

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

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

  useEffect(() => {
      if (typeof inspections === 'object') {
          const newInitialVal = {...initVals};
          Object.keys(initVals).forEach(el => newInitialVal[el] = (inspections)[el])
          setInitialValues(newInitialVal);
      }
  }, [inspections])

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

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


  
    <FormField
        label="InspectionNumber"
    >
        <Field
            name="inspection_number"
            placeholder="InspectionNumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="InspectionType" labelFor="inspection_type">
        <Field name="inspection_type" id="inspection_type" component="select">
          
            <option value="incoming">incoming</option>
          
            <option value="in_process">in_process</option>
          
            <option value="final">final</option>
          
            <option value="audit">audit</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Result" labelFor="result">
        <Field name="result" id="result" component="select">
          
            <option value="pending">pending</option>
          
            <option value="pass">pass</option>
          
            <option value="fail">fail</option>
          
            <option value="conditional_pass">conditional_pass</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="SampleSize"
    >
        <Field
            type="number"
            name="sample_size"
            placeholder="SampleSize"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='Summary' hasTextareaHeight>
        <Field
            name='summary'
            id='summary'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='EvidenceFiles'
            color='info'
            icon={mdiUpload}
            path={'inspections/evidence_files'}
            name='evidence_files'
            id='evidence_files'
            schema={{
                size: undefined,
                formats: undefined,
            }}
            component={FormFilePicker}
          ></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('/inspections/inspections-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditInspectionsPage
