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/medications/medicationsSlice'
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 EditMedicationsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    user: null,
    

    
    
    
    'medication_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'dose_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    dose_unit: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    frequency_type: '',
    

    

    

    

    
    
    

    

    

    
    frequency_interval_hours: '',
    

    

    

    

    

    

    

    

    

    
    
    

    
    frequency_notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    route: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    prescribing_provider: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    pharmacy: null,
    

    
    
    
    'condition_treated': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    start_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    end_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    refill_reminder_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    reminders_enabled: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    is_controlled_substance: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    
    medication_photos: [],
    

    

    
    
    

    
    instructions: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

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

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

  const { id } = router.query

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

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

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

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

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


  

  

  

  

  

  

  

  

  

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

  

  

    

  



  
    <FormField
        label="MedicationName"
    >
        <Field
            name="medication_name"
            placeholder="MedicationName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DoseAmount"
    >
        <Field
            type="number"
            name="dose_amount"
            placeholder="DoseAmount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="DoseUnit" labelFor="dose_unit">
        <Field name="dose_unit" id="dose_unit" component="select">
          
            <option value="mg">mg</option>
          
            <option value="ml">ml</option>
          
            <option value="mcg">mcg</option>
          
            <option value="g">g</option>
          
            <option value="units">units</option>
          
            <option value="puffs">puffs</option>
          
            <option value="drops">drops</option>
          
            <option value="sprays">sprays</option>
          
            <option value="patch">patch</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Frequency" labelFor="frequency_type">
        <Field name="frequency_type" id="frequency_type" component="select">
          
            <option value="once_daily">once_daily</option>
          
            <option value="twice_daily">twice_daily</option>
          
            <option value="three_times_daily">three_times_daily</option>
          
            <option value="every_x_hours">every_x_hours</option>
          
            <option value="weekly">weekly</option>
          
            <option value="monthly">monthly</option>
          
            <option value="as_needed">as_needed</option>
          
            <option value="custom">custom</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="EveryXHours"
    >
        <Field
            type="number"
            name="frequency_interval_hours"
            placeholder="EveryXHours"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="FrequencyNotes" hasTextareaHeight>
        <Field name="frequency_notes" as="textarea" placeholder="FrequencyNotes" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Route" labelFor="route">
        <Field name="route" id="route" component="select">
          
            <option value="oral">oral</option>
          
            <option value="topical">topical</option>
          
            <option value="inhaled">inhaled</option>
          
            <option value="injected">injected</option>
          
            <option value="sublingual">sublingual</option>
          
            <option value="nasal">nasal</option>
          
            <option value="rectal">rectal</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='PrescribingProvider' labelFor='prescribing_provider'>
        <Field
            name='prescribing_provider'
            id='prescribing_provider'
            component={SelectField}
            options={initialValues.prescribing_provider}
            itemRef={'healthcare_providers'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'provider_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Pharmacy' labelFor='pharmacy'>
        <Field
            name='pharmacy'
            id='pharmacy'
            component={SelectField}
            options={initialValues.pharmacy}
            itemRef={'pharmacies'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'pharmacy_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="ConditionTreated"
    >
        <Field
            name="condition_treated"
            placeholder="ConditionTreated"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='RemindMetoTakeIt' labelFor='reminders_enabled'>
        <Field
            name='reminders_enabled'
            id='reminders_enabled'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='ControlledSubstance' labelFor='is_controlled_substance'>
        <Field
            name='is_controlled_substance'
            id='is_controlled_substance'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

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

  



  

  
    <FormField label="Instructions" hasTextareaHeight>
        <Field name="instructions" as="textarea" placeholder="Instructions" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="Notes" hasTextareaHeight>
        <Field name="notes" as="textarea" placeholder="Notes" />
    </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('/medications/medications-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditMedicationsPage
