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/capas/capasSlice'
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 EditCapasPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    
    'capa_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    source: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    owner: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    related_document: null,
    

    
    
    

    
    problem_statement: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    root_cause: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    corrective_actions: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    preventive_actions: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    opened_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    due_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    closed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    capa_files: [],
    

    

    

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

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

  const { id } = router.query

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

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

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

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

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


  
    <FormField
        label="CAPANumber"
    >
        <Field
            name="capa_number"
            placeholder="CAPANumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Source" labelFor="source">
        <Field name="source" id="source" component="select">
          
            <option value="complaint">complaint</option>
          
            <option value="audit">audit</option>
          
            <option value="nonconformance">nonconformance</option>
          
            <option value="process_monitoring">process_monitoring</option>
          
            <option value="supplier">supplier</option>
          
            <option value="management_review">management_review</option>
          
            <option value="risk_management">risk_management</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="open">open</option>
          
            <option value="containment">containment</option>
          
            <option value="investigation">investigation</option>
          
            <option value="action_plan">action_plan</option>
          
            <option value="implementation">implementation</option>
          
            <option value="effectiveness_check">effectiveness_check</option>
          
            <option value="closed">closed</option>
          
            <option value="rejected">rejected</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  
    <FormField label="ProblemStatement" hasTextareaHeight>
        <Field name="problem_statement" as="textarea" placeholder="ProblemStatement" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="RootCause" hasTextareaHeight>
        <Field name="root_cause" as="textarea" placeholder="RootCause" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="CorrectiveActions" hasTextareaHeight>
        <Field name="corrective_actions" as="textarea" placeholder="CorrectiveActions" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="PreventiveActions" hasTextareaHeight>
        <Field name="preventive_actions" as="textarea" placeholder="PreventiveActions" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="OpenedAt"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.opened_at ?
                  new Date(
                      dayjs(initialValues.opened_at).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'opened_at': date})}
          />
      </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='CAPAFiles'
            color='info'
            icon={mdiUpload}
            path={'capas/capa_files'}
            name='capa_files'
            id='capa_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('/capas/capas-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditCapasPage
