/* eslint-disable react/jsx-props-no-spreading */
import React, { FC, useState } from 'react';
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Button,
} from '@material-ui/core';

import { ResponseProps } from 'api/ResponseProps';
import { getRoleObject } from 'api/getRoleObject';
import { setReservation } from 'api/setReservation';
import { SubmitHandler, useForm } from 'react-hook-form';
import { InputField } from 'components/Auth/InputField/InputField';
import { InsertReservationProps } from './Reservation/InsertReservationProps';
import { TripStage } from './Reservation/TripStage';
import { SeniorSearch } from './Reservation/SeniorSearch/SeniorSearch';

type ReservationDialogProps = {
  handleClose: () => void;
  isOpen: boolean;
};
export const ReservationDialog: FC<ReservationDialogProps> = ({
  handleClose,
  isOpen,
}: ReservationDialogProps) => {
  const { control, handleSubmit } = useForm<InsertReservationProps>({
    mode: 'onSubmit',
  });

  const [senior, setSenior] = useState<ResponseProps | null>(null);

  const onSubmit: SubmitHandler<InsertReservationProps> = (
    reservation: InsertReservationProps,
  ) => {
    const filledReservation = reservation;
    getRoleObject().then((role) => {
      filledReservation.insertedBy = role.id;
    });
    filledReservation.driverShift = '';
    filledReservation.senior = senior?.id;
    console.log(filledReservation);
    setReservation(filledReservation);
    handleClose();
  };

  return (
    <div data-testid="ReservationDialog">
      <Dialog
        open={isOpen}
        onClose={handleClose}
        aria-labelledby="form-dialog-title"
      >
        <form onSubmit={handleSubmit(onSubmit)} data-testid="Form">
          <DialogTitle id="form-dialog-title">Book New Reservation</DialogTitle>
          <DialogContent>
            <DialogContentText>
              Write here below the details of your next reservation
            </DialogContentText>

            <SeniorSearch senior={senior} setSenior={setSenior} />
            <InputField
              name="number"
              label="Phone number"
              type="tel"
              control={control}
            />
            <InputField
              name="estimatedBeAt"
              label="Arrive time"
              type="date"
              control={control}
            />
            <TripStage control={control} />
          </DialogContent>
          <DialogActions>
            <Button onClick={handleClose} color="primary">
              Cancel
            </Button>
            <Button type="submit" fullWidth variant="contained" color="primary">
              Insert
            </Button>
          </DialogActions>
        </form>
      </Dialog>
    </div>
  );
};