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

    ref: '',

    status_manual: '',

    status_computed: '',

    client: null,

    vehicle: null,

    start_at: new Date(),

    end_at: new Date(),

    pickup_address: '',

    return_address: '',

    options: '',

    days: '',

    price_per_day: '',

    total_price: '',

    paid_amount: '',

    balance_amount: '',

    guarantee_method: '',

    guarantee_amount: '',

    guarantee_status: '',

    departure_validated_at: new Date(),

    return_validated_at: new Date(),

    notes: '',

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

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

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

  const { reservationsId } = router.query;

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

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

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

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

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

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

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

              <FormField label='StatusManual' labelFor='status_manual'>
                <Field
                  name='status_manual'
                  id='status_manual'
                  component='select'
                >
                  <option value='en_attente'>en_attente</option>

                  <option value='confirmee'>confirmee</option>

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

              <FormField label='StatusComputed' labelFor='status_computed'>
                <Field
                  name='status_computed'
                  id='status_computed'
                  component='select'
                >
                  <option value='a_venir'>a_venir</option>

                  <option value='en_cours'>en_cours</option>

                  <option value='a_restituer'>a_restituer</option>

                  <option value='en_retard'>en_retard</option>

                  <option value='terminee'>terminee</option>

                  <option value='annulee'>annulee</option>

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

              <FormField label='Client' labelFor='client'>
                <Field
                  name='client'
                  id='client'
                  component={SelectField}
                  options={initialValues.client}
                  itemRef={'clients'}
                  showField={'first_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='StartAt'>
                <DatePicker
                  dateFormat='yyyy-MM-dd hh:mm'
                  showTimeSelect
                  selected={
                    initialValues.start_at
                      ? new Date(
                          dayjs(initialValues.start_at).format(
                            'YYYY-MM-DD hh:mm',
                          ),
                        )
                      : null
                  }
                  onChange={(date) =>
                    setInitialValues({ ...initialValues, start_at: date })
                  }
                />
              </FormField>

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

              <FormField label='PickupAddress'>
                <Field name='pickup_address' placeholder='PickupAddress' />
              </FormField>

              <FormField label='ReturnAddress'>
                <Field name='return_address' placeholder='ReturnAddress' />
              </FormField>

              <FormField label='Options'>
                <Field name='options' placeholder='Options' />
              </FormField>

              <FormField label='Days'>
                <Field type='number' name='days' placeholder='Days' />
              </FormField>

              <FormField label='PricePerDay'>
                <Field
                  type='number'
                  name='price_per_day'
                  placeholder='PricePerDay'
                />
              </FormField>

              <FormField label='TotalPrice'>
                <Field
                  type='number'
                  name='total_price'
                  placeholder='TotalPrice'
                />
              </FormField>

              <FormField label='PaidAmount'>
                <Field
                  type='number'
                  name='paid_amount'
                  placeholder='PaidAmount'
                />
              </FormField>

              <FormField label='BalanceAmount'>
                <Field
                  type='number'
                  name='balance_amount'
                  placeholder='BalanceAmount'
                />
              </FormField>

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

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

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

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

              <FormField label='GuaranteeAmount'>
                <Field
                  type='number'
                  name='guarantee_amount'
                  placeholder='GuaranteeAmount'
                />
              </FormField>

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

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

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

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

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

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

              <FormField label='Notes'>
                <Field name='notes' placeholder='Notes' />
              </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('/reservations/reservations-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditReservations;
