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/service_requests/service_requestsSlice'
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 EditService_requestsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    organization: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    customer: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    requester_user: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    assigned_coordinator_user: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    service_package: null,
    

    
    
    

    

    

    

    

    

    

    

    
    service_type: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    timing_preference: '',
    

    

    

    

    
    
    

    

    

    

    

    
    scheduled_start_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    scheduled_end_at: new Date(),
    

    

    

    

    

    

    

    
    
    
    'summary': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    description: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    priority: '',
    

    

    

    

    
    
    
    'estimated_total': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'final_total': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    submitted_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    closed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    requires_no_contact_coordination: false,
    

    

    

    

    

    

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

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

  const { id } = router.query

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

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

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

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

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


  

  

  

  

  

  

  

  

  

  
    {hasPermission(currentUser, 'READ_ORGANIZATIONS') && 
    <FormField label='Organization' labelFor='organization'>
        <Field
            name='organization'
            id='organization'
            component={SelectField}
            options={initialValues.organization}
            itemRef={'organizations'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
     } 

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Customer' labelFor='customer'>
        <Field
            name='customer'
            id='customer'
            component={SelectField}
            options={initialValues.customer}
            itemRef={'customers'}
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'full_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='ServicePackage' labelFor='service_package'>
        <Field
            name='service_package'
            id='service_package'
            component={SelectField}
            options={initialValues.service_package}
            itemRef={'service_packages'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ServiceType" labelFor="service_type">
        <Field name="service_type" id="service_type" component="select">
          
            <option value="retrieval">retrieval</option>
          
            <option value="coordination">coordination</option>
          
            <option value="administrative_support">administrative_support</option>
          
            <option value="concierge_assistance">concierge_assistance</option>
          
            <option value="custom_request">custom_request</option>
          
            <option value="communication_support">communication_support</option>
          
            <option value="premium_coordination">premium_coordination</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="TimingPreference" labelFor="timing_preference">
        <Field name="timing_preference" id="timing_preference" component="select">
          
            <option value="asap">asap</option>
          
            <option value="same_day">same_day</option>
          
            <option value="scheduled">scheduled</option>
          
            <option value="flexible">flexible</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  
    <FormField
        label="RequestSummary"
    >
        <Field
            name="summary"
            placeholder="RequestSummary"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='SituationDescription' hasTextareaHeight>
        <Field
            name='description'
            id='description'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="submitted">submitted</option>
          
            <option value="coordinator_assigned">coordinator_assigned</option>
          
            <option value="in_progress">in_progress</option>
          
            <option value="coordination_active">coordination_active</option>
          
            <option value="review_complete">review_complete</option>
          
            <option value="successfully_closed">successfully_closed</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Priority" labelFor="priority">
        <Field name="priority" id="priority" component="select">
          
            <option value="standard">standard</option>
          
            <option value="rush_priority">rush_priority</option>
          
            <option value="after_hours">after_hours</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="EstimatedTotal"
    >
        <Field
            type="number"
            name="estimated_total"
            placeholder="EstimatedTotal"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="FinalTotal"
    >
        <Field
            type="number"
            name="final_total"
            placeholder="FinalTotal"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='NoContactCoordination' labelFor='requires_no_contact_coordination'>
        <Field
            name='requires_no_contact_coordination'
            id='requires_no_contact_coordination'
            component={SwitchField}
        ></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('/service_requests/service_requests-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditService_requestsPage
