/**
 * Edit Project Memberships 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 { SwitchField } from '../../components/SwitchField';

import {
  update,
  fetch,
} from '../../stores/project_memberships/project_membershipsSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { useEditPageSync } from '../../hooks/useEditPageSync';
import type { ProjectMembership } from '../../types/entities';

const initVals = {
  project: null as ProjectMembership['project'] | null,
  user: null as ProjectMembership['user'] | null,
  access_level: '' as string,
  is_active: false,
  invited_at: new Date() as Date | null,
  accepted_at: new Date() as Date | null,
};

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit project_memberships')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Edit project_memberships'
          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='Access Level' labelFor='access_level'>
                <Field name='access_level' id='access_level' component='select'>
                  <option value='owner'>owner</option>
                  <option value='editor'>editor</option>
                  <option value='reviewer'>reviewer</option>
                  <option value='viewer'>viewer</option>
                </Field>
              </FormField>

              <FormField label='Is Active' labelFor='is_active'>
                <Field
                  name='is_active'
                  id='is_active'
                  component={SwitchField}
                />
              </FormField>

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

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

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

export default EditProject_membershipsPage;
