import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import {
  Alert,
  Button,
  Paper,
  Snackbar,
  TextField,
  Typography,
} from '@mui/material';
import { useForm } from 'react-hook-form';
import { setAdmin } from '../slices/auth/adminSlice';
import { useLoginAdminMutation } from '../slices/api/adminSlice';
import type { Credentials, StatusProps } from '../models';
import { isFetchBaseQueryError } from '../error';
import type { Data } from '../error';

const Status = ({ error, setOpen }: StatusProps) => {
  return isFetchBaseQueryError(error) ? (
    <Alert severity="error" onClose={() => setOpen(false)}>
      {(error.data as Data).message}
    </Alert>
  ) : (
    <Alert severity="error" onClose={() => setOpen(false)}>
      Admin login failed
    </Alert>
  );
};

function GuestLogin() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [login, { isLoading, error }] = useLoginAdminMutation();
  const [open, setOpen] = useState<boolean>(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Credentials>({
    defaultValues: {
      username: '',
      password: '',
    },
  });

  const onSubmit = async (data: Credentials) => {
    try {
      dispatch(setAdmin(await login(data).unwrap()));
      navigate('/dashboard');
    } catch (e) {
      setOpen(true);
    }
  };

  return (
    <form
      style={{
        height: '100%',
        width: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'start',
      }}
      noValidate
      onSubmit={handleSubmit(onSubmit)}
    >
      <Paper
        elevation={3}
        sx={{
          '&:hover': { boxShadow: 8 },
          width: { xs: '90%', md: 400 },
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          mt: 16,
          p: 2,
          borderRadius: '8px',
        }}
      >
        <Typography variant="h6">Admin Login</Typography>
        <TextField
          label="Username"
          variant="outlined"
          margin="normal"
          fullWidth
          error={!!errors.username}
          helperText={errors.username?.message}
          required
          {...register('username', { required: 'This field is required' })}
        />
        <TextField
          label="Password"
          variant="outlined"
          margin="normal"
          fullWidth
          error={!!errors.password}
          helperText={errors.password?.message}
          required
          {...register('password', { required: 'This field is required' })}
        />
        <Button type="submit" variant="contained" fullWidth sx={{ mt: 2 }}>
          Log in
        </Button>
      </Paper>
      <Snackbar
        open={!isLoading && open}
        onClose={() => setOpen(false)}
        autoHideDuration={5000}
      >
        <div>
          <Status {...({ error, setOpen } as StatusProps)} />
        </div>
      </Snackbar>
    </form>
  );
}

export default GuestLogin;
