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/payments/paymentsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import dataFormatter from '../../helpers/dataFormatter';

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

    start_payment_date: new Date(),

    payment_date: new Date(),

    last_payment_paid_date: new Date(),

    sort: '',

    'deduct_amount': '',

    'deduct_paid_amount': '',

    interval: '',

    'interest_amount': '',

    'commission_amount': '',

    'total_amount': '',

    'total_paid_amount': '',

    'penalty_amount': '',

    'pending_amount': '',

    'cross_amount': '',

    'remark': '',

    loan: null,

    status: null,

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

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

  const { id } = router.query

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

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

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

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

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

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

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

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

    <FormField
        label="Sort"
    >
        <Field
            type="number"
            name="sort"
            placeholder="Sort"
        />
    </FormField>

    <FormField
        label="DeductAmount"
    >
        <Field
            type="number"
            name="deduct_amount"
            placeholder="DeductAmount"
        />
    </FormField>

    <FormField
        label="DeductPaidAmount"
    >
        <Field
            type="number"
            name="deduct_paid_amount"
            placeholder="DeductPaidAmount"
        />
    </FormField>

    <FormField
        label="Interval"
    >
        <Field
            type="number"
            name="interval"
            placeholder="Interval"
        />
    </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="TotalAmount"
    >
        <Field
            type="number"
            name="total_amount"
            placeholder="TotalAmount"
        />
    </FormField>

    <FormField
        label="TotalPaidAmount"
    >
        <Field
            type="number"
            name="total_paid_amount"
            placeholder="TotalPaidAmount"
        />
    </FormField>

    <FormField
        label="PenaltyAmount"
    >
        <Field
            type="number"
            name="penalty_amount"
            placeholder="PenaltyAmount"
        />
    </FormField>

    <FormField
        label="PendingAmount"
    >
        <Field
            type="number"
            name="pending_amount"
            placeholder="PendingAmount"
        />
    </FormField>

    <FormField
        label="CrossAmount"
    >
        <Field
            type="number"
            name="cross_amount"
            placeholder="CrossAmount"
        />
    </FormField>

    <FormField
        label="Remark"
    >
        <Field
            name="remark"
            placeholder="Remark"
        />
    </FormField>

  <FormField label='Loan' labelFor='loan'>
        <Field
            name='loan'
            id='loan'
            component={SelectField}
            options={initialValues.loan}
            itemRef={'loans'}

            showField={'code'}

        ></Field>
    </FormField>

  <FormField label='Status' labelFor='status'>
        <Field
            name='status'
            id='status'
            component={SelectField}
            options={initialValues.status}
            itemRef={'payment_status'}

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

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

export default EditPaymentsPage
