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 { SelectField } from "../../components/SelectField";
import { SelectFieldMany } from "../../components/SelectFieldMany";
import { SwitchField } from '../../components/SwitchField'
import {RichTextField} from "../../components/RichTextField";

import { update, fetch } from '../../stores/payment_revenues/payment_revenuesSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'

const EditPayment_revenues = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {

    transaction_date: new Date(),

    'admin_fee_amount': '',

    'interest_amount': '',

    'commission_amount': '',

    'expense_amount': '',

    setlement_datetime: new Date(),

    branch: null,

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

  const { payment_revenues } = useAppSelector((state) => state.payment_revenues)

  const { payment_revenuesId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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

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

    <FormField
        label="AdminFeeAmount"
    >
        <Field
            type="number"
            name="admin_fee_amount"
            placeholder="AdminFeeAmount"
        />
    </FormField>

    <FormField
        label="InterestAmount"
    >
        <Field
            type="number"
            name="interest_amount"
            placeholder="InterestAmount"
        />
    </FormField>

    <FormField
        label="CommissionAmount"
    >
        <Field
            type="number"
            name="commission_amount"
            placeholder="CommissionAmount"
        />
    </FormField>

    <FormField
        label="ExpenseAmount"
    >
        <Field
            type="number"
            name="expense_amount"
            placeholder="ExpenseAmount"
        />
    </FormField>

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

    <FormField label='Branch' labelFor='branch'>
        <Field
            name='branch'
            id='branch'
            component={SelectField}
            options={initialValues.branch}
            itemRef={'branches'}

            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('/payment_revenues/payment_revenues-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

EditPayment_revenues.getLayout = function getLayout(page: ReactElement) {
  return (
      <LayoutAuthenticated>
          {page}
      </LayoutAuthenticated>
  )
}

export default EditPayment_revenues
