import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { Box, Button, Container, 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 (
    <Container component="form" maxWidth="xs" onSubmit={handleSubmit(onSubmit)}>
      <Box sx={{ mt: 8, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Typography variant="h6">
            Guest Login
          </Typography>
          <TextField
            label="First Name"
            variant="outlined"
            margin="normal"
            fullWidth
            required
            {...register("firstName", { required: true })}
          />
          <TextField
            label="Last Name"
            variant="outlined"
            margin="normal"
            fullWidth
            required
            {...register("lastName", { required: true })}
          />
          <Button 
            type="submit" 
            variant="contained" 
            fullWidth
            sx={{ mt: 2 }}
            disabled={!isDirty || !isValid}>
            Login
          </Button>
      </Box>
    </Container>
  );
}

export default GuestLogin;
