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/trials/trialsSlice'
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 EditTrialsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    tenant: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    farm: null,
    

    
    
    
    'name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'code': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    objective: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    planned_start_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    planned_end_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    actual_start_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    actual_end_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    
    protocol_notes: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    

    
    trial_sites: [],
    
    
    

    

    

    

    

    

    

    

    

    

    

    

    
    trial_entries: [],
    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { id } = router.query

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

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Tenant' labelFor='tenant'>
        <Field
            name='tenant'
            id='tenant'
            component={SelectField}
            options={initialValues.tenant}
            itemRef={'tenants'}
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Farm' labelFor='farm'>
        <Field
            name='farm'
            id='farm'
            component={SelectField}
            options={initialValues.farm}
            itemRef={'farms'}
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="TrialName"
    >
        <Field
            name="name"
            placeholder="TrialName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="TrialCode"
    >
        <Field
            name="code"
            placeholder="TrialCode"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='Objective' hasTextareaHeight>
        <Field
            name='objective'
            id='objective'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="planned">planned</option>
          
            <option value="active">active</option>
          
            <option value="completed">completed</option>
          
            <option value="archived">archived</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  
    <FormField label='ProtocolNotes' hasTextareaHeight>
        <Field
            name='protocol_notes'
            id='protocol_notes'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  
      <FormField label='TrialSites' labelFor='trial_sites'>
          <Field
              name='trial_sites'
              id='trial_sites'
              component={SelectFieldMany}
              options={initialValues.trial_sites}
              itemRef={'trial_sites'}
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
              showField={'name'}
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
          ></Field>
      </FormField>
  

    

  



  

  

  

  

  

  

  

  

  

  

  
      <FormField label='TrialEntries' labelFor='trial_entries'>
          <Field
              name='trial_entries'
              id='trial_entries'
              component={SelectFieldMany}
              options={initialValues.trial_entries}
              itemRef={'trial_entries'}
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
              showField={'entry_label'}
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
          ></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('/trials/trials-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditTrialsPage
