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/nonconformances/nonconformancesSlice'
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 EditNonconformancesPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    
    'ncr_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    source: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    item: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    lot: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    production_order: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    inspection: null,
    

    
    
    

    

    

    

    

    

    

    

    
    severity: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    reported_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    reported_by: null,
    

    
    
    

    

    
    description: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    containment_action: '',
    

    

    

    

    

    

    

    

    

    

    
    
    
    'disposition': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    due_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    closed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    attachments: [],
    

    

    

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

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

  const { id } = router.query

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

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

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

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

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


  
    <FormField
        label="NCRNumber"
    >
        <Field
            name="ncr_number"
            placeholder="NCRNumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Source" labelFor="source">
        <Field name="source" id="source" component="select">
          
            <option value="receiving">receiving</option>
          
            <option value="in_process">in_process</option>
          
            <option value="final">final</option>
          
            <option value="customer">customer</option>
          
            <option value="audit">audit</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Item' labelFor='item'>
        <Field
            name='item'
            id='item'
            component={SelectField}
            options={initialValues.item}
            itemRef={'items'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'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='Inspection' labelFor='inspection'>
        <Field
            name='inspection'
            id='inspection'
            component={SelectField}
            options={initialValues.inspection}
            itemRef={'qa_inspections'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'inspection_number'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Severity" labelFor="severity">
        <Field name="severity" id="severity" component="select">
          
            <option value="minor">minor</option>
          
            <option value="major">major</option>
          
            <option value="critical">critical</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="open">open</option>
          
            <option value="containment">containment</option>
          
            <option value="investigation">investigation</option>
          
            <option value="corrective_action">corrective_action</option>
          
            <option value="verified">verified</option>
          
            <option value="closed">closed</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  
    <FormField label='Description' hasTextareaHeight>
        <Field
            name='description'
            id='description'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='ContainmentAction' hasTextareaHeight>
        <Field
            name='containment_action'
            id='containment_action'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Disposition"
    >
        <Field
            name="disposition"
            placeholder="Disposition"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='Attachments'
            color='info'
            icon={mdiUpload}
            path={'nonconformances/attachments'}
            name='attachments'
            id='attachments'
            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('/nonconformances/nonconformances-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditNonconformancesPage
