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

const initVals = {
  project: null as Transition['project'] | null,
  environment: '',
  source_key: '',
  name: '',
  slug: '',
  video_url: '',
  audio_url: '',
  supports_reverse: false,
  duration_sec: '',
};

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

  const transitionsState = useAppSelector((state) => state.transitions);
  const transitions = transitionsState.transitions as
    | Transition
    | Transition[]
    | undefined;
  const transition = Array.isArray(transitions) ? transitions[0] : transitions;

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit transitions')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit transitions'}
          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='VideoURL'>
                <Field name='video_url' placeholder='VideoURL' />
              </FormField>

              <FormField label='AudioURL'>
                <Field name='audio_url' placeholder='AudioURL' />
              </FormField>

              <FormField label='Supportsreverse' labelFor='supports_reverse'>
                <Field
                  name='supports_reverse'
                  id='supports_reverse'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField label='Duration(sec)'>
                <Field
                  type='number'
                  name='duration_sec'
                  placeholder='Duration(sec)'
                />
              </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('/transitions/transitions-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditTransitions;
