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/page_links/page_linksSlice';
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 type { PageLink } from '../../types/entities';

const initVals = {
  from_page: null as PageLink['source_page'] | null,
  to_page: null as PageLink['target_page'] | null,
  direction: '',
  external_url: '',
  transition: null as PageLink['transition'] | null,
  is_active: false,
  trigger_selector: '',
};

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

  const pageLinksState = useAppSelector((state) => state.page_links);
  const page_links = pageLinksState.page_links as
    | PageLink
    | PageLink[]
    | undefined;
  const pageLink = Array.isArray(page_links) ? page_links[0] : page_links;

  const { page_linksId } = router.query;
  const idStr = Array.isArray(page_linksId) ? page_linksId[0] : page_linksId;

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

  useEffect(() => {
    if (pageLink && typeof pageLink === 'object') {
      const newInitialVal = { ...initVals };
      Object.keys(initVals).forEach((el) => {
        if (el in pageLink) {
          (newInitialVal as Record<string, unknown>)[el] = (
            pageLink as unknown as Record<string, unknown>
          )[el];
        }
      });
      setInitialValues(newInitialVal);
    }
  }, [pageLink]);

  const handleSubmit = async (data: typeof initVals) => {
    if (idStr) {
      await dispatch(
        update({ id: idStr, data: data as unknown as Partial<PageLink> }),
      );
      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='Frompage' labelFor='from_page'>
                <Field
                  name='from_page'
                  id='from_page'
                  component={SelectField}
                  options={initialValues.from_page}
                  itemRef={'tour_pages'}
                  showField={'name'}
                ></Field>
              </FormField>

              <FormField label='Topage' labelFor='to_page'>
                <Field
                  name='to_page'
                  id='to_page'
                  component={SelectField}
                  options={initialValues.to_page}
                  itemRef={'tour_pages'}
                  showField={'name'}
                ></Field>
              </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='ExternalURL'>
                <Field name='external_url' placeholder='ExternalURL' />
              </FormField>

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

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

              <FormField label='Triggerselector'>
                <Field name='trigger_selector' placeholder='Triggerselector' />
              </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_links.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission={'UPDATE_PAGE_LINKS'}>
      {page}
    </LayoutAuthenticated>
  );
};

export default EditPage_links;
