import React from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Paper, TextField, Typography } from '@mui/material';
import { useForm } from 'react-hook-form';
import { useAppDispatch } from '../hooks';
import { setGuest } from '../slices/auth/guestSlice';
import { useLoginGuestMutation } from '../slices/api/guestSlice';
import { showSnackbar } from '../slices/snackbarSlice';
import { isFetchBaseQueryError } from '../error';
import type { Data } from '../error';
import type { Name } from '../models';

function GuestLogin() {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const [login] = useLoginGuestMutation();

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Name>({
    defaultValues: {
      firstName: '',
      lastName: '',
    },
  });

  const onSubmit = async (data: Name) => {
    try {
      dispatch(setGuest(await login(data).unwrap()));
      navigate('/rsvp');
    } catch (error) {
      if (isFetchBaseQueryError(error)) {
        dispatch(
          showSnackbar({
            message: (error.data as Data).message,
            severity: 'error',
          })
        );
      } else {
        dispatch(
          showSnackbar({
            message: 'No response',
            severity: 'error',
          })
        );
      }
    }
  };

  return (
    <form
      style={{
        height: '100%',
        width: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'start',
      }}
      noValidate
      onSubmit={handleSubmit(onSubmit)}
    >
      <Paper
        elevation={3}
        sx={{
          '&:hover': { boxShadow: 5 },
          width: { xs: '90%', md: 400 },
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          mt: 16,
          p: 2,
          borderRadius: 2,
        }}
      >
        <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>
      </Paper>
    </form>
  );
}

export default GuestLogin;
