/**
 * Edit Publish Events Page
 */

import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement } 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 { SelectField } from '../../components/SelectField';

import { update, fetch } from '../../stores/publish_events/publish_eventsSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { useEditPageSync } from '../../hooks/useEditPageSync';
import type { PublishEvent } from '../../types/entities';

const initVals = {
  project: null as PublishEvent['project'] | null,
  user: null as PublishEvent['user'] | null,
  from_environment: '' as string,
  to_environment: '' as string,
  started_at: new Date() as Date | null,
  finished_at: new Date() as Date | null,
  status: '' as string,
  error_message: '',
  pages_copied: '' as string | number,
  transitions_copied: '' as string | number,
  audios_copied: '' as string | number,
};

const EditPublish_eventsPage = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();

  const {
    values: initialValues,
    setValues,
    id,
  } = useEditPageSync({
    entitySelector: (state) => state.publish_events.publish_events,
    fetchAction: fetch,
    initialValues: initVals,
  });

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit publish_events')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Edit publish_events'
          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'
                />
              </FormField>

              <FormField label='User' labelFor='user'>
                <Field
                  name='user'
                  id='user'
                  component={SelectField}
                  options={initialValues.user}
                  itemRef='users'
                  showField='firstName'
                />
              </FormField>

              <FormField label='From Environment' labelFor='from_environment'>
                <Field
                  name='from_environment'
                  id='from_environment'
                  component='select'
                >
                  <option value='dev'>dev</option>
                  <option value='stage'>stage</option>
                  <option value='production'>production</option>
                </Field>
              </FormField>

              <FormField label='To Environment' labelFor='to_environment'>
                <Field
                  name='to_environment'
                  id='to_environment'
                  component='select'
                >
                  <option value='dev'>dev</option>
                  <option value='stage'>stage</option>
                  <option value='production'>production</option>
                </Field>
              </FormField>

              <FormField label='Started At'>
                <DatePicker
                  dateFormat='yyyy-MM-dd hh:mm'
                  showTimeSelect
                  selected={
                    initialValues.started_at
                      ? new Date(
                          dayjs(initialValues.started_at).format(
                            'YYYY-MM-DD hh:mm',
                          ),
                        )
                      : null
                  }
                  onChange={(date: Date | null) =>
                    setValues({
                      ...initialValues,
                      started_at: date,
                    })
                  }
                />
              </FormField>

              <FormField label='Finished At'>
                <DatePicker
                  dateFormat='yyyy-MM-dd hh:mm'
                  showTimeSelect
                  selected={
                    initialValues.finished_at
                      ? new Date(
                          dayjs(initialValues.finished_at).format(
                            'YYYY-MM-DD hh:mm',
                          ),
                        )
                      : null
                  }
                  onChange={(date: Date | null) =>
                    setValues({
                      ...initialValues,
                      finished_at: date,
                    })
                  }
                />
              </FormField>

              <FormField label='Status' labelFor='status'>
                <Field name='status' id='status' component='select'>
                  <option value='queued'>queued</option>
                  <option value='running'>running</option>
                  <option value='success'>success</option>
                  <option value='failed'>failed</option>
                </Field>
              </FormField>

              <FormField label='Error Message' hasTextareaHeight>
                <Field
                  name='error_message'
                  as='textarea'
                  placeholder='Error Message'
                />
              </FormField>

              <FormField label='Pages Copied'>
                <Field
                  type='number'
                  name='pages_copied'
                  placeholder='Pages Copied'
                />
              </FormField>

              <FormField label='Transitions Copied'>
                <Field
                  type='number'
                  name='transitions_copied'
                  placeholder='Transitions Copied'
                />
              </FormField>

              <FormField label='Audios Copied'>
                <Field
                  type='number'
                  name='audios_copied'
                  placeholder='Audios Copied'
                />
              </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('/publish_events/publish_events-list')
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditPublish_eventsPage;
