/**
 * Edit Presigned URL Requests 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/presigned_url_requests/presigned_url_requestsSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { useEditPageSync } from '../../hooks/useEditPageSync';
import type { PresignedUrlRequest } from '../../types/entities';

const initVals = {
  project: null,
  user: null,
  purpose: '',
  asset_type: '',
  requested_key: '',
  mime_type: '',
  requested_size_mb: '',
  expires_at: new Date(),
  status: '',
};

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit presigned_url_requests')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Edit presigned_url_requests'
          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='Purpose' labelFor='purpose'>
                <Field name='purpose' id='purpose' component='select'>
                  <option value='upload'>upload</option>
                  <option value='download'>download</option>
                </Field>
              </FormField>

              <FormField label='Asset Type' labelFor='asset_type'>
                <Field name='asset_type' id='asset_type' component='select'>
                  <option value='image'>image</option>
                  <option value='video'>video</option>
                  <option value='audio'>audio</option>
                  <option value='file'>file</option>
                </Field>
              </FormField>

              <FormField label='Requested Key'>
                <Field name='requested_key' placeholder='Requested Key' />
              </FormField>

              <FormField label='MIME Type'>
                <Field name='mime_type' placeholder='MIME Type' />
              </FormField>

              <FormField label='Requested Size (MB)'>
                <Field
                  type='number'
                  name='requested_size_mb'
                  placeholder='Requested Size (MB)'
                />
              </FormField>

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

              <FormField label='Status'>
                <Field name='status' placeholder='Status' />
              </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(
                      '/presigned_url_requests/presigned_url_requests-list',
                    )
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

EditPresigned_url_requestsPage.getLayout = function getLayout(
  page: ReactElement,
) {
  return (
    <LayoutAuthenticated permission='UPDATE_PRESIGNED_URL_REQUESTS'>
      {page}
    </LayoutAuthenticated>
  );
};

export default EditPresigned_url_requestsPage;
