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/receipts/receiptsSlice'
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 EditReceipts = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    merchant: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    uploaded_by: null,
    

    
    
    

    

    

    

    

    

    

    

    
    receipt_kind: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    
    receipt_images: [],
    

    

    
    
    

    

    

    

    

    

    

    

    

    
    receipt_files: [],
    

    

    

    
    
    
    'source_channel': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    captured_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    ocr_status: '',
    

    

    

    

    
    
    
    'ocr_confidence': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    needs_review: false,
    

    

    

    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { receiptsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit receipts')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit receipts'} 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='UploadedBy' labelFor='uploaded_by'>
        <Field
            name='uploaded_by'
            id='uploaded_by'
            component={SelectField}
            options={initialValues.uploaded_by}
            itemRef={'users'}
      
        
            showField={'firstName'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ReceiptKind" labelFor="receipt_kind">
        <Field name="receipt_kind" id="receipt_kind" component="select">
          
            <option value="sales">sales</option>
          
            <option value="purchase">purchase</option>
          
            <option value="expense">expense</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    
        <FormField>
            <Field
                label='ReceiptImages'
                color='info'
                icon={mdiUpload}
                path={'receipts/receipt_images'}
                name='receipt_images'
                id='receipt_images'
                schema={{
                    size: undefined,
                    formats: undefined,
                }}
                component={FormImagePicker}
            ></Field>
        </FormField>
    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='ReceiptFiles'
            color='info'
            icon={mdiUpload}
            path={'receipts/receipt_files'}
            name='receipt_files'
            id='receipt_files'
            schema={{
                size: undefined,
                formats: undefined,
            }}
            component={FormFilePicker}
          ></Field>
        </FormField>
  



  
    <FormField
        label="SourceChannel"
    >
        <Field
            name="source_channel"
            placeholder="SourceChannel"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="OCRStatus" labelFor="ocr_status">
        <Field name="ocr_status" id="ocr_status" component="select">
          
            <option value="pending">pending</option>
          
            <option value="processing">processing</option>
          
            <option value="completed">completed</option>
          
            <option value="failed">failed</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="OCRConfidence"
    >
        <Field
            type="number"
            name="ocr_confidence"
            placeholder="OCRConfidence"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='NeedsReview' labelFor='needs_review'>
        <Field
            name='needs_review'
            id='needs_review'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

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

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

export default EditReceipts
