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/audits/auditsSlice'
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 EditAudits = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    
    'audit_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    audit_type: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    lead_auditor: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    supplier: null,
    

    
    
    

    

    

    

    

    
    start_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    end_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    
    scope: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    summary: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    audit_files: [],
    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    

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

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

  const { auditsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  
    <FormField
        label="AuditNumber"
    >
        <Field
            name="audit_number"
            placeholder="AuditNumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="AuditType" labelFor="audit_type">
        <Field name="audit_type" id="audit_type" component="select">
          
            <option value="internal">internal</option>
          
            <option value="supplier">supplier</option>
          
            <option value="notified_body">notified_body</option>
          
            <option value="regulatory">regulatory</option>
          
            <option value="certification">certification</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="planned">planned</option>
          
            <option value="in_progress">in_progress</option>
          
            <option value="report_issued">report_issued</option>
          
            <option value="closed">closed</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  
    <FormField label="Scope" hasTextareaHeight>
        <Field name="scope" as="textarea" placeholder="Scope" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="Summary" hasTextareaHeight>
        <Field name="summary" as="textarea" placeholder="Summary" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

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



  

  

  

  

  

  

  

  

  

  

  
      <FormField label='MappedClauses' labelFor='mapped_clauses'>
          <Field
              name='mapped_clauses'
              id='mapped_clauses'
              component={SelectFieldMany}
              options={initialValues.mapped_clauses}
              itemRef={'clauses'}
            
            
            
            
            
            
            
            
            
            
            
            
              showField={'clause_code'}
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
          ></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('/audits/audits-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditAudits
