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

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

  const project_membershipsState = useAppSelector(
    (state) => state.project_memberships,
  );
  const project_memberships = project_membershipsState.project_memberships as
    | ProjectMembership
    | ProjectMembership[]
    | undefined;
  const item = Array.isArray(project_memberships)
    ? project_memberships[0]
    : project_memberships;

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

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

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

  const handleSubmit = async (data: typeof initVals) => {
    if (project_membershipsId) {
      await dispatch(
        update({
          id: project_membershipsId,
          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'}
                ></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='Accesslevel' 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='Isactive' labelFor='is_active'>
                <Field
                  name='is_active'
                  id='is_active'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField label='Invitedat'>
                <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) =>
                    setInitialValues({ ...initialValues, invited_at: date })
                  }
                />
              </FormField>

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

export default EditProject_memberships;
