import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { Button, Grid, Paper, TextField, Typography } from '@mui/material';

import { setCredentials } from './authSlice';
import { useLoginMutation } from '../../apiSlice';
import type { LoginRequest } from './authSlice';

function GuestLogin() {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  // TODO: use react-hook-form
  const [formState, setFormState] = useState<LoginRequest>({
    firstName: '',
    lastName: ''
  });

  const [login] = useLoginMutation();

  const handleChange = ({
    target: { name, value },
  }: React.ChangeEvent<HTMLInputElement>) =>
    setFormState(prev => ({ ...prev, [name]: value }));

  const handleSubmit = async () => {
      try {
        const user = await login(formState).unwrap();
        dispatch(setCredentials(user));
        navigate('/rsvp');
      } catch (e) {
        console.log(e);
      }
  };

  return (
    <Paper>
      <Grid container spacing={2}>
        <Grid item xs={12} md={12} lg={12}>
          <Typography variant="h6">
            Guest Login
          </Typography>
        </Grid>
        <Grid item xs={12} md={6} lg={6}>
          <TextField label="First Name" variant="outlined" onChange={handleChange} />
        </Grid>
        <Grid item xs={12} md={6} lg={6}>
          <TextField label="Last Name" variant="outlined" onChange={handleChange} />
        </Grid>
        <Grid item>
          <Button onClick={handleSubmit} variant="contained">
            Login
          </Button>
        </Grid>
      </Grid>
    </Paper>
  );
}

export default GuestLogin;
