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/period_settings/period_settingsSlice';
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 EditPeriod_settings = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const initVals = {
    school: null,

    total_periods_per_day: '',

    period_duration: '',

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

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

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

  const { period_settingsId } = router.query;

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

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

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

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

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

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

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

              <FormField label='TotalPeriodsPerDay'>
                <Field
                  type='number'
                  name='total_periods_per_day'
                  placeholder='TotalPeriodsPerDay'
                />
              </FormField>

              <FormField label='PeriodDuration(minutes)'>
                <Field
                  type='number'
                  name='period_duration'
                  placeholder='PeriodDuration(minutes)'
                />
              </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('/period_settings/period_settings-list')
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditPeriod_settings;
