/**
 * Edit PWA Caches 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 { SwitchField } from '../../components/SwitchField';

import { update, fetch } from '../../stores/pwa_caches/pwa_cachesSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { useEditPageSync } from '../../hooks/useEditPageSync';

const initVals = {
  project: null,
  environment: '',
  cache_version: '',
  manifest_json: '',
  asset_list_json: '',
  generated_at: new Date(),
  is_active: false,
};

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

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

  const handleSubmit = async (data: typeof initVals) => {
    if (id) {
      await dispatch(update({ id, data }));
      await router.push('/pwa_caches/pwa_caches-list');
    }
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit pwa_caches')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Edit pwa_caches'
          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='Environment' labelFor='environment'>
                <Field name='environment' id='environment' component='select'>
                  <option value='stage'>stage</option>
                  <option value='production'>production</option>
                </Field>
              </FormField>

              <FormField label='Cache Version'>
                <Field name='cache_version' placeholder='Cache Version' />
              </FormField>

              <FormField label='Manifest JSON' hasTextareaHeight>
                <Field
                  name='manifest_json'
                  as='textarea'
                  placeholder='Manifest JSON'
                />
              </FormField>

              <FormField label='Asset List JSON' hasTextareaHeight>
                <Field
                  name='asset_list_json'
                  as='textarea'
                  placeholder='Asset List JSON'
                />
              </FormField>

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

              <FormField label='Is Active' labelFor='is_active'>
                <Field
                  name='is_active'
                  id='is_active'
                  component={SwitchField}
                />
              </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('/pwa_caches/pwa_caches-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditPwa_cachesPage;
