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/agreements/agreementsSlice'
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 EditAgreements = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    company: null,
    

    
    
    
    'agreement_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    driver: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    vehicle: null,
    

    
    
    

    

    

    

    

    

    

    

    
    agreement_type: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    billing_frequency: '',
    

    

    

    

    
    
    
    'daily_rate': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'weekly_rate': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'monthly_rate': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    deposit_required: false,
    

    

    

    

    

    

    
    
    
    'deposit_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    start_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    end_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    recurring_invoice_enabled: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    created_on: new Date(),
    

    

    

    

    

    

    

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

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

  const { agreementsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Company' labelFor='company'>
        <Field
            name='company'
            id='company'
            component={SelectField}
            options={initialValues.company}
            itemRef={'companies'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="AgreementNumber"
    >
        <Field
            name="agreement_number"
            placeholder="AgreementNumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Driver' labelFor='driver'>
        <Field
            name='driver'
            id='driver'
            component={SelectField}
            options={initialValues.driver}
            itemRef={'drivers'}
      
        
      
        
      
        
      
        
      
        
            showField={'driver_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Vehicle' labelFor='vehicle'>
        <Field
            name='vehicle'
            id='vehicle'
            component={SelectField}
            options={initialValues.vehicle}
            itemRef={'vehicles'}
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'plate_no'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="AgreementType" labelFor="agreement_type">
        <Field name="agreement_type" id="agreement_type" component="select">
          
            <option value="rental">rental</option>
          
            <option value="lease">lease</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="BillingFrequency" labelFor="billing_frequency">
        <Field name="billing_frequency" id="billing_frequency" component="select">
          
            <option value="daily">daily</option>
          
            <option value="weekly">weekly</option>
          
            <option value="monthly">monthly</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DailyRate"
    >
        <Field
            type="number"
            name="daily_rate"
            placeholder="DailyRate"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="WeeklyRate"
    >
        <Field
            type="number"
            name="weekly_rate"
            placeholder="WeeklyRate"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="MonthlyRate"
    >
        <Field
            type="number"
            name="monthly_rate"
            placeholder="MonthlyRate"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='DepositRequired' labelFor='deposit_required'>
        <Field
            name='deposit_required'
            id='deposit_required'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  
    <FormField
        label="DepositAmount"
    >
        <Field
            type="number"
            name="deposit_amount"
            placeholder="DepositAmount"
        />
    </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='RecurringInvoiceEnabled' labelFor='recurring_invoice_enabled'>
        <Field
            name='recurring_invoice_enabled'
            id='recurring_invoice_enabled'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="active">active</option>
          
            <option value="paused">paused</option>
          
            <option value="ended">ended</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  
    <FormField label="Notes" hasTextareaHeight>
        <Field name="notes" as="textarea" placeholder="Notes" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="CreatedOn"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.created_on ?
                  new Date(
                      dayjs(initialValues.created_on).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'created_on': date})}
          />
      </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('/agreements/agreements-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditAgreements
