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 EnhancedEntityEditShell from '../../components/EntityPage/EnhancedEntityEditShell'

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/field_verifications/field_verificationsSlice'
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";

import {hasPermission} from "../../helpers/userPermissions";



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

    

    

    

    

    

    

    

    

    

    

    
    project: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    verified_by_user: null,
    

    
    
    

    

    

    

    

    
    visit_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    verification_type: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    outcome: '',
    

    

    

    

    
    
    

    

    
    findings: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    
    actions_required: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    next_followup_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    
    photos: [],
    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

  const { field_verifications } = useAppSelector((state) => state.field_verifications)
  
  const { currentUser } = useAppSelector((state) => state.auth);
  

  const { id } = router.query

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit field_verifications')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit field_verifications'} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <EnhancedEntityEditShell
                entityLabel="Field Verification"
                pluralLabel="Field Verifications"
                listHref="/field_verifications/field_verifications-list"
                viewHref={`/field_verifications/field_verifications-view/?id=${id}`}
                record={initialValues}
              >
<FormField label='Project' labelFor='project'>
        <Field
            name='project'
            id='project'
            component={SelectField}
            options={initialValues.project}
            itemRef={'projects'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="VerificationType" labelFor="verification_type">
        <Field name="verification_type" id="verification_type" component="select">
          
            <option value="site_visit">site_visit</option>
          
            <option value="remote_validation">remote_validation</option>
          
            <option value="document_review">document_review</option>
          
            <option value="stakeholder_interview">stakeholder_interview</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Outcome" labelFor="outcome">
        <Field name="outcome" id="outcome" component="select">
          
            <option value="pass">pass</option>
          
            <option value="partial">partial</option>
          
            <option value="fail">fail</option>
          
            <option value="follow_up_required">follow_up_required</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  
    <FormField label='Findings' hasTextareaHeight>
        <Field
            name='findings'
            id='findings'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="ActionsRequired" hasTextareaHeight>
        <Field name="actions_required" as="textarea" placeholder="ActionsRequired" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    
        <FormField>
            <Field
                label='Photos'
                color='info'
                icon={mdiUpload}
                path={'field_verifications/photos'}
                name='photos'
                id='photos'
                schema={{
                    size: undefined,
                    formats: undefined,
                }}
                component={FormImagePicker}
            ></Field>
        </FormField>
    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='organizations' labelFor='organizations'>
        <Field
            name='organizations'
            id='organizations'
            component={SelectField}
            options={initialValues.organizations}
            itemRef={'organizations'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></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('/field_verifications/field_verifications-list')}/>
              </BaseButtons>
              </EnhancedEntityEditShell>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditField_verificationsPage
