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/guarantees/guaranteesSlice';
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 EditGuarantees = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const initVals = {
    tenant: null,

    reservation: null,

    method: '',

    amount: '',

    status: '',

    proof_url: '',

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

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

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

  const { guaranteesId } = router.query;

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

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

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit guarantees')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit guarantees'}
          main
        >
          {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <FormField label='Tenant' labelFor='tenant'>
                <Field
                  name='tenant'
                  id='tenant'
                  component={SelectField}
                  options={initialValues.tenant}
                  itemRef={'tenants'}
                  showField={'name'}
                ></Field>
              </FormField>

              <FormField label='Reservation' labelFor='reservation'>
                <Field
                  name='reservation'
                  id='reservation'
                  component={SelectField}
                  options={initialValues.reservation}
                  itemRef={'reservations'}
                  showField={'ref'}
                ></Field>
              </FormField>

              <FormField label='Method' labelFor='method'>
                <Field name='method' id='method' component='select'>
                  <option value='especes'>especes</option>

                  <option value='carte_bloquee'>carte_bloquee</option>

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

              <FormField label='Amount'>
                <Field type='number' name='amount' placeholder='Amount' />
              </FormField>

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

                  <option value='restituee'>restituee</option>

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

              <FormField label='ProofURL'>
                <Field name='proof_url' placeholder='ProofURL' />
              </FormField>

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

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

export default EditGuarantees;
