import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } 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, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import type { PwaCache } from '../../types/entities';

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

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

  const pwaCachesState = useAppSelector((state) => state.pwa_caches);
  const pwa_caches = pwaCachesState.pwa_caches as
    | PwaCache
    | PwaCache[]
    | undefined;
  const pwaCache = Array.isArray(pwa_caches) ? pwa_caches[0] : pwa_caches;

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

  // Fetch entity data
  useEffect(() => {
    if (pwa_cachesId) {
      dispatch(fetch({ id: pwa_cachesId }));
    }
  }, [pwa_cachesId, dispatch]);

  // Sync form values with fetched data
  useEffect(() => {
    if (typeof pwaCache === 'object' && pwaCache !== null) {
      const newInitialVal = { ...initVals };
      Object.keys(initVals).forEach((key) => {
        if (key in pwaCache) {
          (newInitialVal as Record<string, unknown>)[key] = (
            pwaCache as unknown as Record<string, unknown>
          )[key];
        }
      });
      setInitialValues(newInitialVal);
    }
  }, [pwaCache]);

  const handleSubmit = async (data: typeof initVals) => {
    if (pwa_cachesId) {
      await dispatch(
        update({
          id: pwa_cachesId,
          data: data as unknown as Partial<PwaCache>,
        }),
      );
    }
    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'}
                ></Field>
              </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='Cacheversion'>
                <Field name='cache_version' placeholder='Cacheversion' />
              </FormField>

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

              <FormField label='AssetlistJSON' hasTextareaHeight>
                <Field
                  name='asset_list_json'
                  as='textarea'
                  placeholder='AssetlistJSON'
                />
              </FormField>

              <FormField label='Generatedat'>
                <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) =>
                    setInitialValues({ ...initialValues, generated_at: date })
                  }
                />
              </FormField>

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

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

export default EditPwa_caches;
