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 {
  update,
  fetch,
} from '../../stores/presigned_url_requests/presigned_url_requestsSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
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_requests = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [initialValues, setInitialValues] = useState(initVals);

  const presignedState = useAppSelector(
    (state) => state.presigned_url_requests,
  );
  const presigned_url_requests = presignedState.presigned_url_requests as
    | PresignedUrlRequest
    | PresignedUrlRequest[]
    | undefined;
  const presignedRequest = Array.isArray(presigned_url_requests)
    ? presigned_url_requests[0]
    : presigned_url_requests;

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

  useEffect(() => {
    if (presigned_url_requestsId) {
      dispatch(fetch({ id: presigned_url_requestsId }));
    }
  }, [presigned_url_requestsId, dispatch]);

  useEffect(() => {
    if (typeof presignedRequest === 'object' && presignedRequest !== null) {
      const newInitialVal = { ...initVals };
      Object.keys(initVals).forEach((key) => {
        if (key in presignedRequest) {
          (newInitialVal as Record<string, unknown>)[key] = (
            presignedRequest as unknown as Record<string, unknown>
          )[key];
        }
      });
      setInitialValues(newInitialVal);
    }
  }, [presignedRequest]);

  const handleSubmit = async (data: typeof initVals) => {
    if (presigned_url_requestsId) {
      await dispatch(
        update({
          id: presigned_url_requestsId,
          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'}
                ></Field>
              </FormField>

              <FormField label='User' labelFor='user'>
                <Field
                  name='user'
                  id='user'
                  component={SelectField}
                  options={initialValues.user}
                  itemRef={'users'}
                  showField={'firstName'}
                ></Field>
              </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='Assettype' 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='Requestedkey'>
                <Field name='requested_key' placeholder='Requestedkey' />
              </FormField>

              <FormField label='MIMEtype'>
                <Field name='mime_type' placeholder='MIMEtype' />
              </FormField>

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

              <FormField label='Expiresat'>
                <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) =>
                    setInitialValues({
                      ...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_requests.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission={'UPDATE_PRESIGNED_URL_REQUESTS'}>
      {page}
    </LayoutAuthenticated>
  );
};

export default EditPresigned_url_requests;
