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/treatments/treatmentsSlice'
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 EditTreatments = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    poultry_lot: null,
    

    
    
    

    

    

    

    

    

    

    

    
    treatment_type: '',
    

    

    

    

    
    
    
    'product_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'dosage': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    administered_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    next_due_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    performed_by_user: null,
    

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

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

  const { treatmentsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Type" labelFor="treatment_type">
        <Field name="treatment_type" id="treatment_type" component="select">
          
            <option value="vaccination">vaccination</option>
          
            <option value="medication">medication</option>
          
            <option value="vitamins">vitamins</option>
          
            <option value="disinfection">disinfection</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="Produit/Médicament"
    >
        <Field
            name="product_name"
            placeholder="Produit/Médicament"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Dosage"
    >
        <Field
            name="dosage"
            placeholder="Dosage"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Statut" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="planned">planned</option>
          
            <option value="done">done</option>
          
            <option value="missed">missed</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  
    <FormField label="Notes" hasTextareaHeight>
        <Field name="notes" as="textarea" placeholder="Notes" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Effectuépar' labelFor='performed_by_user'>
        <Field
            name='performed_by_user'
            id='performed_by_user'
            component={SelectField}
            options={initialValues.performed_by_user}
            itemRef={'users'}
      
        
            showField={'firstName'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></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('/treatments/treatments-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditTreatments
