/**
 * Edit Access Logs 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/access_logs/access_logsSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { useEditPageSync } from '../../hooks/useEditPageSync';
import type { AccessLog } from '../../types/entities';

const initVals = {
  project: null as unknown,
  environment: '' as '' | 'admin' | 'stage' | 'production',
  user: null as unknown,
  path: '',
  ip_address: '',
  user_agent: '',
  accessed_at: new Date(),
};

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit access_logs')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Edit access_logs'
          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='admin'>admin</option>
                  <option value='stage'>stage</option>
                  <option value='production'>production</option>
                </Field>
              </FormField>

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

              <FormField label='Path'>
                <Field name='path' placeholder='Path' />
              </FormField>

              <FormField label='IP Address'>
                <Field name='ip_address' placeholder='IP Address' />
              </FormField>

              <FormField label='User Agent' hasTextareaHeight>
                <Field
                  name='user_agent'
                  as='textarea'
                  placeholder='User Agent'
                />
              </FormField>

              <FormField label='Accessed At'>
                <DatePicker
                  dateFormat='yyyy-MM-dd hh:mm'
                  showTimeSelect
                  selected={
                    initialValues.accessed_at
                      ? new Date(
                          dayjs(initialValues.accessed_at).format(
                            'YYYY-MM-DD hh:mm',
                          ),
                        )
                      : null
                  }
                  onChange={(date: Date | null) =>
                    setValues({
                      ...initialValues,
                      accessed_at: date || new Date(),
                    })
                  }
                />
              </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('/access_logs/access_logs-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditAccess_logsPage;
