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

import {
  update,
  fetch,
} from '../../stores/compliance_issues/compliance_issuesSlice';
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 { hasPermission } from '../../helpers/userPermissions';

const EditCompliance_issues = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const initVals = {
    organization: null,

    category: '',

    description: '',

    severity: '',

    owner: null,

    status: '',

    organizations: null,
  };
  const [initialValues, setInitialValues] = useState(initVals);

  const { compliance_issues } = useAppSelector(
    (state) => state.compliance_issues,
  );

  const { currentUser } = useAppSelector((state) => state.auth);

  const { compliance_issuesId } = router.query;

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

  useEffect(() => {
    if (typeof compliance_issues === 'object') {
      setInitialValues(compliance_issues);
    }
  }, [compliance_issues]);

  useEffect(() => {
    if (typeof compliance_issues === 'object') {
      const newInitialVal = { ...initVals };

      Object.keys(initVals).forEach(
        (el) => (newInitialVal[el] = compliance_issues[el]),
      );

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

  const handleSubmit = async (data) => {
    await dispatch(update({ id: compliance_issuesId, data }));
    await router.push('/compliance_issues/compliance_issues-list');
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit compliance_issues')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit compliance_issues'}
          main
        >
          {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              {hasPermission(currentUser, 'READ_ORGANIZATIONS') && (
                <FormField label='Organization' labelFor='organization'>
                  <Field
                    name='organization'
                    id='organization'
                    component={SelectField}
                    options={initialValues.organization}
                    itemRef={'organizations'}
                    showField={'name'}
                  ></Field>
                </FormField>
              )}

              <FormField label='Category' labelFor='category'>
                <Field name='category' id='category' component='select'>
                  <option value='security'>security</option>

                  <option value='privacy'>privacy</option>

                  <option value='billing'>billing</option>
                </Field>
              </FormField>

              <FormField label='Description'>
                <Field name='description' placeholder='Description' />
              </FormField>

              <FormField label='Severity' labelFor='severity'>
                <Field name='severity' id='severity' component='select'>
                  <option value='low'>low</option>

                  <option value='medium'>medium</option>

                  <option value='high'>high</option>

                  <option value='critical'>critical</option>
                </Field>
              </FormField>

              <FormField label='Owner' labelFor='owner'>
                <Field
                  name='owner'
                  id='owner'
                  component={SelectField}
                  options={initialValues.owner}
                  itemRef={'users'}
                  showField={'firstName'}
                ></Field>
              </FormField>

              <FormField label='Status' labelFor='status'>
                <Field name='status' id='status' component='select'>
                  <option value='open'>open</option>

                  <option value='in_progress'>in_progress</option>

                  <option value='resolved'>resolved</option>
                </Field>
              </FormField>

              <FormField label='organizations' labelFor='organizations'>
                <Field
                  name='organizations'
                  id='organizations'
                  component={SelectField}
                  options={initialValues.organizations}
                  itemRef={'organizations'}
                  showField={'name'}
                ></Field>
              </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('/compliance_issues/compliance_issues-list')
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditCompliance_issues;
