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

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

    'code': '',

    'principal_amount': '',

    term: '',

    'pending_amount': '',

    'last_pending_amount': '',

    'rate': '',

    'commission_rate': '',

    registration_date: new Date(),

    started_payment_date: new Date(),

    last_payment_date: new Date(),

    finish_payment_date: new Date(),

    'finish_discount': '',

    'finish_discount_amount': '',

    'admin_rate': '',

    'admin_amount': '',

    'purpose': '',

    status: null,

    client: null,

    staff: null,

    interest_rate: null,

    branch: null,

    loan_type: null,

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

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

  const { id } = router.query

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

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

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

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

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

    <FormField
        label="Code"
    >
        <Field
            name="code"
            placeholder="Code"
        />
    </FormField>

    <FormField
        label="PrincipalAmount"
    >
        <Field
            type="number"
            name="principal_amount"
            placeholder="PrincipalAmount"
        />
    </FormField>

    <FormField
        label="Term"
    >
        <Field
            type="number"
            name="term"
            placeholder="Term"
        />
    </FormField>

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

    <FormField
        label="LastPendingAmount"
    >
        <Field
            type="number"
            name="last_pending_amount"
            placeholder="LastPendingAmount"
        />
    </FormField>

    <FormField
        label="Rate"
    >
        <Field
            type="number"
            name="rate"
            placeholder="Rate"
        />
    </FormField>

    <FormField
        label="CommissionRate"
    >
        <Field
            type="number"
            name="commission_rate"
            placeholder="CommissionRate"
        />
    </FormField>

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

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

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

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

    <FormField
        label="FinishDiscount"
    >
        <Field
            type="number"
            name="finish_discount"
            placeholder="FinishDiscount"
        />
    </FormField>

    <FormField
        label="FinishDiscountAmount"
    >
        <Field
            type="number"
            name="finish_discount_amount"
            placeholder="FinishDiscountAmount"
        />
    </FormField>

    <FormField
        label="AdminRate"
    >
        <Field
            type="number"
            name="admin_rate"
            placeholder="AdminRate"
        />
    </FormField>

    <FormField
        label="AdminAmount"
    >
        <Field
            type="number"
            name="admin_amount"
            placeholder="AdminAmount"
        />
    </FormField>

    <FormField
        label="Purpose"
    >
        <Field
            name="purpose"
            placeholder="Purpose"
        />
    </FormField>

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

            showField={'name'}

        ></Field>
    </FormField>

  <FormField label='Client' labelFor='client'>
        <Field
            name='client'
            id='client'
            component={SelectField}
            options={initialValues.client}
            itemRef={'clients'}

            showField={'name_en'}

        ></Field>
    </FormField>

  <FormField label='Staff' labelFor='staff'>
        <Field
            name='staff'
            id='staff'
            component={SelectField}
            options={initialValues.staff}
            itemRef={'staffs'}

            showField={'name_en'}

        ></Field>
    </FormField>

  <FormField label='InterestRate' labelFor='interest_rate'>
        <Field
            name='interest_rate'
            id='interest_rate'
            component={SelectField}
            options={initialValues.interest_rate}
            itemRef={'interest_rates'}

            showField={'name'}

        ></Field>
    </FormField>

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

            showField={'name'}

        ></Field>
    </FormField>

  <FormField label='LoanType' labelFor='loan_type'>
        <Field
            name='loan_type'
            id='loan_type'
            component={SelectField}
            options={initialValues.loan_type}
            itemRef={'loan_types'}

            showField={'name_en'}

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

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

export default EditLoansPage
