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/tour_pages/tour_pagesSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import type { TourPage } from '../../types/entities';

const initVals = {
  project: null as TourPage['project'] | null,
  environment: '',
  source_key: '',
  name: '',
  slug: '',
  sort_order: '',
  background_image_url: '',
  background_video_url: '',
  background_audio_url: '',
  background_loop: false,
  requires_auth: false,
  ui_schema_json: '',
};

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

  const tourPagesState = useAppSelector((state) => state.tour_pages);
  const tour_pages = tourPagesState.tour_pages as
    | TourPage
    | TourPage[]
    | undefined;
  const tourPage = Array.isArray(tour_pages) ? tour_pages[0] : tour_pages;

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

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

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

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

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

              <FormField label='Environment' labelFor='environment'>
                <Field name='environment' id='environment' component='select'>
                  <option value='dev'>dev</option>

                  <option value='stage'>stage</option>

                  <option value='production'>production</option>
                </Field>
              </FormField>

              <FormField label='Sourcekey'>
                <Field name='source_key' placeholder='Sourcekey' />
              </FormField>

              <FormField label='Name'>
                <Field name='name' placeholder='Name' />
              </FormField>

              <FormField label='Slug'>
                <Field name='slug' placeholder='Slug' />
              </FormField>

              <FormField label='Sortorder'>
                <Field
                  type='number'
                  name='sort_order'
                  placeholder='Sortorder'
                />
              </FormField>

              <FormField label='BackgroundimageURL'>
                <Field
                  name='background_image_url'
                  placeholder='BackgroundimageURL'
                />
              </FormField>

              <FormField label='BackgroundvideoURL'>
                <Field
                  name='background_video_url'
                  placeholder='BackgroundvideoURL'
                />
              </FormField>

              <FormField label='BackgroundaudioURL'>
                <Field
                  name='background_audio_url'
                  placeholder='BackgroundaudioURL'
                />
              </FormField>

              <FormField label='Backgroundloop' labelFor='background_loop'>
                <Field
                  name='background_loop'
                  id='background_loop'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField label='Requiresauth' labelFor='requires_auth'>
                <Field
                  name='requires_auth'
                  id='requires_auth'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField label='UIschemaJSON' hasTextareaHeight>
                <Field
                  name='ui_schema_json'
                  as='textarea'
                  placeholder='UIschemaJSON'
                />
              </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('/tour_pages/tour_pages-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditTour_pages;
