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/expenses/expensesSlice'
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 EditExpenses = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    merchant: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    receipt: null,
    

    
    
    

    

    

    

    

    

    

    

    
    category: '',
    

    

    

    

    
    
    
    'description': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    expense_date: new Date(),
    

    

    

    

    

    

    

    
    
    
    'amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    tax_treatment: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    entered_by: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    reviewed_by: null,
    

    
    
    

    

    

    

    

    
    reviewed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    
    review_notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { expensesId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Merchant' labelFor='merchant'>
        <Field
            name='merchant'
            id='merchant'
            component={SelectField}
            options={initialValues.merchant}
            itemRef={'merchants'}
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'business_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Receipt' labelFor='receipt'>
        <Field
            name='receipt'
            id='receipt'
            component={SelectField}
            options={initialValues.receipt}
            itemRef={'receipts'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'source_channel'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Category" labelFor="category">
        <Field name="category" id="category" component="select">
          
            <option value="rent">rent</option>
          
            <option value="utilities">utilities</option>
          
            <option value="salary">salary</option>
          
            <option value="transport">transport</option>
          
            <option value="office">office</option>
          
            <option value="marketing">marketing</option>
          
            <option value="maintenance">maintenance</option>
          
            <option value="bank_fees">bank_fees</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="Description"
    >
        <Field
            name="description"
            placeholder="Description"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Amount"
    >
        <Field
            type="number"
            name="amount"
            placeholder="Amount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="TaxTreatment" labelFor="tax_treatment">
        <Field name="tax_treatment" id="tax_treatment" component="select">
          
            <option value="deductible">deductible</option>
          
            <option value="non_deductible">non_deductible</option>
          
            <option value="capitalizable">capitalizable</option>
          
            <option value="unknown">unknown</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="submitted">submitted</option>
          
            <option value="approved">approved</option>
          
            <option value="rejected">rejected</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

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

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

export default EditExpenses
