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/payouts/payoutsSlice'
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 EditPayouts = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    tenant: null,
    

    
    
    
    'payout_reference': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    recipient_user: null,
    

    
    
    

    

    

    

    

    

    

    

    
    payout_method: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    payout_status: '',
    

    

    

    

    
    
    
    'gross_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'fee_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'net_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    scheduled_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    processed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    paid_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    payout_proof_files: [],
    

    

    

    
    
    

    
    note: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { payoutsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Tenant' labelFor='tenant'>
        <Field
            name='tenant'
            id='tenant'
            component={SelectField}
            options={initialValues.tenant}
            itemRef={'tenants'}
      
        
      
        
      
        
      
        
      
        
            showField={'tenant_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="PayoutReference"
    >
        <Field
            name="payout_reference"
            placeholder="PayoutReference"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="PayoutMethod" labelFor="payout_method">
        <Field name="payout_method" id="payout_method" component="select">
          
            <option value="bank_transfer">bank_transfer</option>
          
            <option value="ewallet">ewallet</option>
          
            <option value="cash">cash</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="PayoutStatus" labelFor="payout_status">
        <Field name="payout_status" id="payout_status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="scheduled">scheduled</option>
          
            <option value="processing">processing</option>
          
            <option value="paid">paid</option>
          
            <option value="failed">failed</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="GrossAmount"
    >
        <Field
            type="number"
            name="gross_amount"
            placeholder="GrossAmount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="FeeAmount"
    >
        <Field
            type="number"
            name="fee_amount"
            placeholder="FeeAmount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="NetAmount"
    >
        <Field
            type="number"
            name="net_amount"
            placeholder="NetAmount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

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



  

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

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

export default EditPayouts
