import React from "react";

import LoadingButton from "@mui/lab/LoadingButton";
import Box from "@mui/material/Box";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";

import { useSnackbar } from "notistack";

import { useApi } from "../contexts/ApiContext";
import { useI18n } from "../contexts/I18nContext";
import { useUser } from "../contexts/UserContext";
import { title } from "../util";

const LoginForm: React.FC = () => {
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useI18n();
  const { login } = useUser();
  const api = useApi();

  const [username, setUsername] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);

  const operation = api.operations["bananas.login:create"];
  const { properties } = operation.request.body.schema;

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    setLoading(true);

    login(username, password)
      .then((user) => {
        if (user != null) {
          enqueueSnackbar(`${t("Welcome,")} ${user.full_name}`, {
            variant: "success",
          });
        } else {
          enqueueSnackbar(t("Unable to log in with provided credentials."), {
            variant: "error",
          });
        }
      })
      .finally(() => setLoading(false));
  };

  return (
    <Box component="form" onSubmit={handleSubmit}>
      <DialogContent>
        <Stack spacing={1}>
          <TextField
            fullWidth
            color={"secondary"}
            inputProps={{ "aria-label": "Username" }}
            label={title(t(properties.username.title.toLowerCase()))}
            name="username"
            type="text"
            onChange={(e) => setUsername(e.target.value)}
          />
          <TextField
            fullWidth
            color="secondary"
            inputProps={{ "aria-label": "Password" }}
            label={t(properties.password.title)}
            name="password"
            type="password"
            onChange={(e) => setPassword(e.target.value)}
          />
        </Stack>
      </DialogContent>

      <DialogActions
        sx={{
          pt: 0,
          pb: 2,
        }}
      >
        <LoadingButton
          aria-label="login"
          color="primary"
          loading={loading}
          sx={{ margin: "auto" }}
          type="submit"
          variant="contained"
        >
          {t("Log in")}
        </LoadingButton>
      </DialogActions>
    </Box>
  );
};

export default LoginForm;
