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/recurring_invoice_templates/recurring_invoice_templatesSlice'
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 EditRecurring_invoice_templates = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    company: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    agreement: null,
    

    
    
    

    

    

    

    

    

    

    

    
    billing_frequency: '',
    

    

    

    

    
    
    
    'rate': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    next_run_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    last_run_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    active_flag: false,
    

    

    

    

    

    

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

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

  const { recurring_invoice_templatesId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit recurring_invoice_templates')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit recurring_invoice_templates'} 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='Agreement' labelFor='agreement'>
        <Field
            name='agreement'
            id='agreement'
            component={SelectField}
            options={initialValues.agreement}
            itemRef={'agreements'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'agreement_number'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></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="Rate"
    >
        <Field
            type="number"
            name="rate"
            placeholder="Rate"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='Active' labelFor='active_flag'>
        <Field
            name='active_flag'
            id='active_flag'
            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('/recurring_invoice_templates/recurring_invoice_templates-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditRecurring_invoice_templates
