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/transactions/transactionsSlice'
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 EditTransactionsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    workspace: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    financial_account: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    data_connection: null,
    

    
    
    

    

    

    

    

    
    posted_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    effective_at: new Date(),
    

    

    

    

    

    

    

    
    
    
    'amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'currency': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    description: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'merchant_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    direction: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    category: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    classification_status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    vendor: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    customer: null,
    

    
    
    
    'external_reference': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    is_recurring_candidate: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { id } = router.query

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

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Workspace' labelFor='workspace'>
        <Field
            name='workspace'
            id='workspace'
            component={SelectField}
            options={initialValues.workspace}
            itemRef={'workspaces'}
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='FinancialAccount' labelFor='financial_account'>
        <Field
            name='financial_account'
            id='financial_account'
            component={SelectField}
            options={initialValues.financial_account}
            itemRef={'financial_accounts'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'account_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='DataConnection' labelFor='data_connection'>
        <Field
            name='data_connection'
            id='data_connection'
            component={SelectField}
            options={initialValues.data_connection}
            itemRef={'data_connections'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'provider_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

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

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Currency"
    >
        <Field
            name="currency"
            placeholder="Currency"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

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

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="MerchantName"
    >
        <Field
            name="merchant_name"
            placeholder="MerchantName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Direction" labelFor="direction">
        <Field name="direction" id="direction" component="select">
          
            <option value="inflow">inflow</option>
          
            <option value="outflow">outflow</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Category" labelFor="category">
        <Field name="category" id="category" component="select">
          
            <option value="revenue">revenue</option>
          
            <option value="cogs">cogs</option>
          
            <option value="payroll">payroll</option>
          
            <option value="rent">rent</option>
          
            <option value="software">software</option>
          
            <option value="marketing">marketing</option>
          
            <option value="travel">travel</option>
          
            <option value="tax">tax</option>
          
            <option value="interest">interest</option>
          
            <option value="other_expense">other_expense</option>
          
            <option value="other_income">other_income</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ClassificationStatus" labelFor="classification_status">
        <Field name="classification_status" id="classification_status" component="select">
          
            <option value="unreviewed">unreviewed</option>
          
            <option value="auto_classified">auto_classified</option>
          
            <option value="confirmed">confirmed</option>
          
            <option value="needs_attention">needs_attention</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Vendor' labelFor='vendor'>
        <Field
            name='vendor'
            id='vendor'
            component={SelectField}
            options={initialValues.vendor}
            itemRef={'vendors'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'vendor_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  
    <FormField
        label="ExternalReference"
    >
        <Field
            name="external_reference"
            placeholder="ExternalReference"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

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

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

export default EditTransactionsPage
