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/expansion_plans/expansion_plansSlice';
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 EditExpansion_plans = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const initVals = {
    organization: null,

    territory: '',

    status: '',

    projected_roi_pct: '',

    start_date: new Date(),

    approval_status: '',

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

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

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

  const { expansion_plansId } = router.query;

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

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

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit expansion_plans')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit expansion_plans'}
          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='Territory'>
                <Field name='territory' placeholder='Territory' />
              </FormField>

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

                  <option value='active'>active</option>

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

              <FormField label='ProjectedROIPercentage'>
                <Field
                  type='number'
                  name='projected_roi_pct'
                  placeholder='ProjectedROIPercentage'
                />
              </FormField>

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

              <FormField label='ApprovalStatus' labelFor='approval_status'>
                <Field
                  name='approval_status'
                  id='approval_status'
                  component='select'
                >
                  <option value='pending'>pending</option>

                  <option value='approved'>approved</option>

                  <option value='rejected'>rejected</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('/expansion_plans/expansion_plans-list')
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditExpansion_plans;
