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

    vehicle: null,

    reservation: null,

    ref_no: '',

    date: new Date(),

    location: '',

    amount: '',

    status: '',

    proof_url: '',

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

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

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

  const { infractionsId } = router.query;

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

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

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit infractions')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit infractions'}
          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='Vehicle' labelFor='vehicle'>
                <Field
                  name='vehicle'
                  id='vehicle'
                  component={SelectField}
                  options={initialValues.vehicle}
                  itemRef={'vehicles'}
                  showField={'plate_number'}
                ></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='ReferenceNumber'>
                <Field name='ref_no' placeholder='ReferenceNumber' />
              </FormField>

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

              <FormField label='Location'>
                <Field name='location' placeholder='Location' />
              </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='ouverte'>ouverte</option>

                  <option value='payee'>payee</option>

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

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

export default EditInfractions;
