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/enrollment/enrollmentSlice';
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';

const EditEnrollment = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const initVals = {
    class: null,

    parent: null,

    language: '',

    board: '',

    enrollmentmonth: '',

    studentname: '',

    age: '',

    gender: '',

    nationality: '',

    dateofbirth: new Date(),

    marksheeturl: '',

    parentgovtidurl: '',

    studentgovtidurl: '',

    feeamount: '',

    freetrial: false,

    paymentmethod: '',

    paymentstatus: '',

    transactionid: '',
  };
  const [initialValues, setInitialValues] = useState(initVals);

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

  const { enrollmentId } = router.query;

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

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

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit enrollment')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit enrollment'}
          main
        >
          {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <FormField label='Class' labelFor='class'>
                <Field
                  name='class'
                  id='class'
                  component={SelectField}
                  options={initialValues.class}
                  itemRef={'classes'}
                  showField={'subject'}
                ></Field>
              </FormField>

              <FormField label='Parent' labelFor='parent'>
                <Field
                  name='parent'
                  id='parent'
                  component={SelectField}
                  options={initialValues.parent}
                  itemRef={'parents'}
                  showField={'first_name'}
                ></Field>
              </FormField>

              <FormField label='Language'>
                <Field name='language' placeholder='Language' />
              </FormField>

              <FormField label='Board'>
                <Field name='board' placeholder='Board' />
              </FormField>

              <FormField label='Enrollmentmonth'>
                <Field name='enrollmentmonth' placeholder='Enrollmentmonth' />
              </FormField>

              <FormField label='Studentname'>
                <Field name='studentname' placeholder='Studentname' />
              </FormField>

              <FormField label='Age'>
                <Field type='number' name='age' placeholder='Age' />
              </FormField>

              <FormField label='Gender'>
                <Field name='gender' placeholder='Gender' />
              </FormField>

              <FormField label='Nationality'>
                <Field name='nationality' placeholder='Nationality' />
              </FormField>

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

              <FormField label='Marksheeturl'>
                <Field name='marksheeturl' placeholder='Marksheeturl' />
              </FormField>

              <FormField label='Parentgovtidurl'>
                <Field name='parentgovtidurl' placeholder='Parentgovtidurl' />
              </FormField>

              <FormField label='Studentgovtidurl'>
                <Field name='studentgovtidurl' placeholder='Studentgovtidurl' />
              </FormField>

              <FormField label='Feeamount'>
                <Field type='number' name='feeamount' placeholder='Feeamount' />
              </FormField>

              <FormField label='Freetrial' labelFor='freetrial'>
                <Field
                  name='freetrial'
                  id='freetrial'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField label='Paymentmethod'>
                <Field name='paymentmethod' placeholder='Paymentmethod' />
              </FormField>

              <FormField label='Paymentstatus'>
                <Field name='paymentstatus' placeholder='Paymentstatus' />
              </FormField>

              <FormField label='Transactionid'>
                <Field name='transactionid' placeholder='Transactionid' />
              </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('/enrollment/enrollment-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditEnrollment;
