import { mdiChartTimelineVariant, mdiUpload } 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 FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { SwitchField } from '../../components/SwitchField';

import { update, fetch } from '../../stores/access_logs/access_logsSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import type { AccessLog } from '../../types/entities';

const EditAccess_logs = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  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 [initialValues, setInitialValues] = useState(initVals);

  const { access_logs } = useAppSelector((state) => state.access_logs);

  const { access_logsId } = router.query;
  const accessLogIdStr = Array.isArray(access_logsId)
    ? access_logsId[0]
    : access_logsId;

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

  useEffect(() => {
    if (
      access_logs &&
      typeof access_logs === 'object' &&
      !Array.isArray(access_logs)
    ) {
      const newInitialVal = { ...initVals };

      Object.keys(initVals).forEach(
        (el) =>
          (newInitialVal[el as keyof typeof initVals] = (
            access_logs as Record<string, unknown>
          )[el] as never),
      );

      setInitialValues(newInitialVal);
    }
  }, [access_logs]);

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

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

              <FormField label='IPaddress'>
                <Field name='ip_address' placeholder='IPaddress' />
              </FormField>

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

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

export default EditAccess_logs;
