import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';

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 { SelectFieldMany } from '../../components/SelectFieldMany';

import { update, fetch } from '../../stores/roles/rolesSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import type { Role } from '../../types/entities';

const initVals = {
  name: '',
  permissions: [] as unknown[],
};

const EditRoles = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [initialValues, setInitialValues] = useState(initVals);

  const rolesState = useAppSelector((state) => state.roles);
  const roles = rolesState.roles as Role | Role[] | undefined;
  const role = Array.isArray(roles) ? roles[0] : roles;

  const { rolesId } = router.query as { rolesId?: string };

  // Fetch entity data
  useEffect(() => {
    if (rolesId) {
      dispatch(fetch({ id: rolesId }));
    }
  }, [rolesId, dispatch]);

  // Sync form values with fetched data
  useEffect(() => {
    if (typeof role === 'object' && role !== null) {
      const newInitialVal = { ...initVals };
      Object.keys(initVals).forEach((key) => {
        if (key in role) {
          (newInitialVal as Record<string, unknown>)[key] = (
            role as unknown as Record<string, unknown>
          )[key];
        }
      });
      setInitialValues(newInitialVal);
    }
  }, [role]);

  const handleSubmit = async (data: typeof initVals) => {
    if (rolesId) {
      await dispatch(
        update({ id: rolesId, data: data as unknown as Partial<Role> }),
      );
    }
    await router.push('/roles/roles-list');
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit roles')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit roles'}
          main
        >
          {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <FormField label='Name'>
                <Field name='name' placeholder='Name' />
              </FormField>

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

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

export default EditRoles;
