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/fee_payments/fee_paymentsSlice';
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 EditFee_payments = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const initVals = {
    student: null,

    amount_paid: '',

    payment_date: new Date(),

    receipt_url: '',

    term: '',

    status: '',

    schools: null,
  };
  const [initialValues, setInitialValues] = useState(initVals);

  const { fee_payments } = useAppSelector((state) => state.fee_payments);

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

  const { fee_paymentsId } = router.query;

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

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

  useEffect(() => {
    if (typeof fee_payments === 'object') {
      const newInitialVal = { ...initVals };

      Object.keys(initVals).forEach(
        (el) => (newInitialVal[el] = fee_payments[el]),
      );

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit fee_payments')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit fee_payments'}
          main
        >
          {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <FormField label='Student' labelFor='student'>
                <Field
                  name='student'
                  id='student'
                  component={SelectField}
                  options={initialValues.student}
                  itemRef={'students'}
                  showField={'full_name'}
                ></Field>
              </FormField>

              <FormField label='AmountPaid'>
                <Field
                  type='number'
                  name='amount_paid'
                  placeholder='AmountPaid'
                />
              </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='ReceiptURL'>
                <Field name='receipt_url' placeholder='ReceiptURL' />
              </FormField>

              <FormField label='Term'>
                <Field name='term' placeholder='Term' />
              </FormField>

              <FormField label='Status' labelFor='status'>
                <Field name='status' id='status' component='select'>
                  <option value='pending'>pending</option>

                  <option value='completed'>completed</option>

                  <option value='failed'>failed</option>
                </Field>
              </FormField>

              <FormField label='schools' labelFor='schools'>
                <Field
                  name='schools'
                  id='schools'
                  component={SelectField}
                  options={initialValues.schools}
                  itemRef={'schools'}
                  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('/fee_payments/fee_payments-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

EditFee_payments.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission={'UPDATE_FEE_PAYMENTS'}>
      {page}
    </LayoutAuthenticated>
  );
};

export default EditFee_payments;
