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

const initVals = {
  project: null as ProjectAudioTrack['project'] | null,
  environment: '' as string,
  source_key: '',
  name: '',
  slug: '',
  url: '',
  loop: false,
  volume: '' as string | number,
  sort_order: '' as string | number,
  is_enabled: false,
};

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

  const project_audio_tracksState = useAppSelector(
    (state) => state.project_audio_tracks,
  );
  const project_audio_tracks =
    project_audio_tracksState.project_audio_tracks as
      | ProjectAudioTrack
      | ProjectAudioTrack[]
      | undefined;
  const item = Array.isArray(project_audio_tracks)
    ? project_audio_tracks[0]
    : project_audio_tracks;

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

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

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

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

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

              <FormField label='Loop' labelFor='loop'>
                <Field name='loop' id='loop' component={SwitchField}></Field>
              </FormField>

              <FormField label='Volume'>
                <Field type='number' name='volume' placeholder='Volume' />
              </FormField>

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

              <FormField label='Isenabled' labelFor='is_enabled'>
                <Field
                  name='is_enabled'
                  id='is_enabled'
                  component={SwitchField}
                ></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(
                      '/project_audio_tracks/project_audio_tracks-list',
                    )
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditProject_audio_tracks;
