/**
 * Edit Page Links Page
 * Cleaned up version with consolidated useEffect hooks
 */

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

import { update, fetch } from '../../stores/page_links/page_linksSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';

const initVals = {
  from_page: null,
  to_page: null,
  direction: '',
  external_url: '',
  transition: null,
  is_active: false,
  trigger_selector: '',
};

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

  const { page_links } = useAppSelector((state) => state.page_links);
  const { id } = router.query;

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

  // Sync form values with fetched data (consolidated from redundant useEffects)
  useEffect(() => {
    if (typeof page_links === 'object' && page_links !== null) {
      const newInitialVal = { ...initVals };
      Object.keys(initVals).forEach((key) => {
        if (key in page_links) {
          newInitialVal[key] = page_links[key];
        }
      });
      setInitialValues(newInitialVal);
    }
  }, [page_links]);

  const handleSubmit = async (data: typeof initVals) => {
    await dispatch(update({ id: id as string, data }));
    await router.push('/page_links/page_links-list');
  };

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

              <FormField label='To Page' labelFor='to_page'>
                <Field
                  name='to_page'
                  id='to_page'
                  component={SelectField}
                  options={initialValues.to_page}
                  itemRef='tour_pages'
                  showField='name'
                />
              </FormField>

              <FormField label='Direction' labelFor='direction'>
                <Field name='direction' id='direction' component='select'>
                  <option value='forward'>forward</option>
                  <option value='back'>back</option>
                  <option value='external'>external</option>
                </Field>
              </FormField>

              <FormField label='External URL'>
                <Field name='external_url' placeholder='External URL' />
              </FormField>

              <FormField label='Transition' labelFor='transition'>
                <Field
                  name='transition'
                  id='transition'
                  component={SelectField}
                  options={initialValues.transition}
                  itemRef='transitions'
                  showField='name'
                />
              </FormField>

              <FormField label='Is Active' labelFor='is_active'>
                <Field
                  name='is_active'
                  id='is_active'
                  component={SwitchField}
                />
              </FormField>

              <FormField label='Trigger Selector'>
                <Field name='trigger_selector' placeholder='Trigger Selector' />
              </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('/page_links/page_links-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditPage_linksPage;
