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

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

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = 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
      style={{
        height: '100%',
        width: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'start',
      }}
      noValidate
      onSubmit={handleSubmit(onSubmit)}
    >
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
          width: '90%',
        }}
      >
        <div
          style={{
            width: 384,
            marginTop: 128,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center',
          }}
        >
          <Typography variant="h6">Guest Login</Typography>
          <TextField
            label="First Name"
            variant="outlined"
            margin="normal"
            fullWidth
            error={!!errors.firstName}
            helperText={errors.firstName?.message}
            required
            {...register('firstName', { required: 'This field is required' })}
          />
          <TextField
            label="Last Name"
            variant="outlined"
            margin="normal"
            fullWidth
            error={!!errors.lastName}
            helperText={errors.lastName?.message}
            required
            {...register('lastName', { required: 'This field is required' })}
          />
          <Button type="submit" variant="contained" fullWidth sx={{ mt: 2 }}>
            Log in
          </Button>
        </div>
      </div>
    </form>
  );
}

export default GuestLogin;
