import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { Button, Stack, TextField, Typography } from '@mui/material';
import { useForm } from 'react-hook-form';
import { setCredentials } from './authSlice';
import { useLoginMutation, LoginRequest } from '../../apiSlice';

function GuestLogin() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [login] = useLoginMutation();

  const { register, handleSubmit,
  formState: { isDirty, isValid } } = useForm<LoginRequest>({
    defaultValues: {
      firstName: '',
      lastName: ''
    }
  });

  const onSubmit = async (data: LoginRequest) => {
      try {
        dispatch(setCredentials(await login(data).unwrap()));
        navigate('/rsvp');
      } catch (e) {
        console.log(e);
      }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Stack spacing={2}>
          <Typography variant="h6">
            Guest Login
          </Typography>
          <TextField
            label="First Name"
            variant="outlined"
            required
            {...register("firstName", { required: true })}
          />
          <TextField
            label="Last Name"
            variant="outlined"
            required
            {...register("lastName", { required: true })}
          />
          <Button type="submit" variant="contained" disabled={!isDirty || !isValid}>
            Login
          </Button>
      </Stack>
    </form>
  );
}

export default GuestLogin;
