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/consultations/consultationsSlice'
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 EditConsultations = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    appointment: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    patient: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    primary_doctor: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    secondary_doctor: null,
    

    
    
    

    

    

    

    

    
    started_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    ended_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    channel: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    consultation_status: '',
    

    

    

    

    
    
    

    
    chief_complaint: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    clinical_notes: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    
    diagnosis_summary: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    attachments: [],
    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { consultationsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Appointment' labelFor='appointment'>
        <Field
            name='appointment'
            id='appointment'
            component={SelectField}
            options={initialValues.appointment}
            itemRef={'appointments'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'reason'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Patient' labelFor='patient'>
        <Field
            name='patient'
            id='patient'
            component={SelectField}
            options={initialValues.patient}
            itemRef={'patient_profiles'}
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'patient_identifier'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='PrimaryDoctor' labelFor='primary_doctor'>
        <Field
            name='primary_doctor'
            id='primary_doctor'
            component={SelectField}
            options={initialValues.primary_doctor}
            itemRef={'doctor_profiles'}
      
        
      
        
      
        
      
        
      
        
            showField={'specialization'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='SecondaryDoctor' labelFor='secondary_doctor'>
        <Field
            name='secondary_doctor'
            id='secondary_doctor'
            component={SelectField}
            options={initialValues.secondary_doctor}
            itemRef={'doctor_profiles'}
      
        
      
        
      
        
      
        
      
        
            showField={'specialization'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Channel" labelFor="channel">
        <Field name="channel" id="channel" component="select">
          
            <option value="in_person">in_person</option>
          
            <option value="chat">chat</option>
          
            <option value="video">video</option>
          
            <option value="phone">phone</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ConsultationStatus" labelFor="consultation_status">
        <Field name="consultation_status" id="consultation_status" component="select">
          
            <option value="open">open</option>
          
            <option value="closed">closed</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  
    <FormField label="ChiefComplaint" hasTextareaHeight>
        <Field name="chief_complaint" as="textarea" placeholder="ChiefComplaint" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='ClinicalNotes' hasTextareaHeight>
        <Field
            name='clinical_notes'
            id='clinical_notes'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="DiagnosisSummary" hasTextareaHeight>
        <Field name="diagnosis_summary" as="textarea" placeholder="DiagnosisSummary" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='Attachments'
            color='info'
            icon={mdiUpload}
            path={'consultations/attachments'}
            name='attachments'
            id='attachments'
            schema={{
                size: undefined,
                formats: undefined,
            }}
            component={FormFilePicker}
          ></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('/consultations/consultations-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditConsultations
