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/reminders/remindersSlice'
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 EditRemindersPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    patient: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    prescription_item: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    patient_vaccination: null,
    

    
    
    

    

    

    

    

    

    

    

    
    reminder_type: '',
    

    

    

    

    
    
    

    

    

    

    

    
    scheduled_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    sent_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    channel: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    delivery_status: '',
    

    

    

    

    
    
    

    
    message_text: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { id } = router.query

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

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <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='PrescriptionItem' labelFor='prescription_item'>
        <Field
            name='prescription_item'
            id='prescription_item'
            component={SelectField}
            options={initialValues.prescription_item}
            itemRef={'prescription_items'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'frequency'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='PatientVaccination' labelFor='patient_vaccination'>
        <Field
            name='patient_vaccination'
            id='patient_vaccination'
            component={SelectField}
            options={initialValues.patient_vaccination}
            itemRef={'patient_vaccinations'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'notes'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ReminderType" labelFor="reminder_type">
        <Field name="reminder_type" id="reminder_type" component="select">
          
            <option value="medicine">medicine</option>
          
            <option value="vaccination">vaccination</option>
          
            <option value="appointment">appointment</option>
          
            <option value="follow_up">follow_up</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Channel" labelFor="channel">
        <Field name="channel" id="channel" component="select">
          
            <option value="push">push</option>
          
            <option value="email">email</option>
          
            <option value="sms">sms</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="DeliveryStatus" labelFor="delivery_status">
        <Field name="delivery_status" id="delivery_status" component="select">
          
            <option value="pending">pending</option>
          
            <option value="sent">sent</option>
          
            <option value="delivered">delivered</option>
          
            <option value="failed">failed</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

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

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

export default EditRemindersPage
