import VisibilityIcon from "@mui/icons-material/Visibility";
import VisibilityOffIcon from "@mui/icons-material/VisibilityOff";
import {
  Alert,
  CircularProgress,
  FormControl,
  IconButton,
  InputAdornment,
  InputLabel,
  OutlinedInput,
  Tooltip,
} from "@mui/material";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Grid from "@mui/material/Grid";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import * as React from "react";
import { Link, useNavigate } from "react-router-dom";
import { useAuth } from "../../App";
import { AuthApi, PasswordLoginResult } from "../../api/AuthApi";
import { ServerApi } from "../../api/ServerApi";

/**
 * Login form
 */
export function LoginRoute(): React.ReactElement {
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  const auth = useAuth();
  const navigate = useNavigate();

  const [mail, setMail] = React.useState("");
  const [password, setPassword] = React.useState("");

  const canSubmit = mail.length > 0 && password.length > 0;

  const [showPassword, setShowPassword] = React.useState(false);
  const handleClickShowPassword = () => setShowPassword((show) => !show);

  const handleMouseDownPassword = (
    event: React.MouseEvent<HTMLButtonElement>
  ) => {
    event.preventDefault();
  };

  const handleLoginSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!canSubmit) return;

    try {
      const res = await AuthApi.LoginWithPassword(mail, password);

      switch (res) {
        case PasswordLoginResult.TooManyRequests:
          setError(
            "Trop de tentatives de connection. Veuillez réessayer ultérieurement."
          );
          break;

        case PasswordLoginResult.InvalidCredentials:
          setError("Identifiants saisis invalides !");
          break;

        case PasswordLoginResult.Success:
          navigate("/");
          auth.setSignedIn(true);
          break;

        case PasswordLoginResult.Error:
          setError("Echec de la connexion !");
          break;
      }
    } catch (e) {
      console.error(e);
      setError("Echec de l'authentification !");
    }
    setLoading(false);
  };

  const authWithProvider = async (id: string) => {
    try {
      setLoading(true);

      const res = await AuthApi.StartOpenIDLogin(id);
      window.location.href = res.url;
    } catch (e) {
      console.error(e);
      setError("Echec de l'initialisation de l'authentification OpenID !");
    }
  };

  if (loading)
    return (
      <>
        <CircularProgress />
      </>
    );

  return (
    <>
      {error && (
        <Alert style={{ width: "100%" }} severity="error">
          {error}
        </Alert>
      )}

      <Typography component="h2" variant="body1">
        Connexion
      </Typography>
      <Box
        component="form"
        noValidate
        onSubmit={handleLoginSubmit}
        sx={{ mt: 1 }}
      >
        <TextField
          margin="normal"
          required
          fullWidth
          id="email"
          label="Adresse mail"
          name="email"
          value={mail}
          onChange={(e) => setMail(e.target.value)}
          autoComplete="email"
          autoFocus
        />

        <FormControl fullWidth variant="outlined">
          <InputLabel htmlFor="password">Mot de passe</InputLabel>
          <OutlinedInput
            required
            fullWidth
            name="password"
            label="Mot de passe"
            type={showPassword ? "text" : "password"}
            id="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="current-password"
            endAdornment={
              <InputAdornment position="end">
                <Tooltip title="Afficher le mot de passe">
                  <IconButton
                    aria-label="toggle password visibility"
                    onClick={handleClickShowPassword}
                    onMouseDown={handleMouseDownPassword}
                    edge="end"
                  >
                    {showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
                  </IconButton>
                </Tooltip>
              </InputAdornment>
            }
          />
        </FormControl>

        <Button
          type="submit"
          fullWidth
          variant="contained"
          sx={{ mt: 3, mb: 2 }}
          disabled={!canSubmit}
        >
          Connexion
        </Button>

        <Grid container>
          <Grid size={"grow"}>
            <Typography variant="body2" color={"primary"}>
              <Link
                to="/password_forgotten"
                style={{ color: "inherit", textDecorationColor: "inherit" }}
              >
                Mot de passe oublié
              </Link>
            </Typography>
          </Grid>
          <Grid>
            <Typography variant="body2" color={"primary"}>
              <Link
                to="/new-account"
                style={{ color: "inherit", textDecorationColor: "inherit" }}
              >
                Créer un nouveau compte
              </Link>
            </Typography>
          </Grid>
        </Grid>

        <div>
          {ServerApi.Config.oidc_providers.map((p) => (
            <Button
              key={p.id}
              style={{ textAlign: "center", width: "100%", marginTop: "20px" }}
              onClick={() => authWithProvider(p.id)}
            >
              Connexion avec {p.name}
            </Button>
          ))}
        </div>
      </Box>
    </>
  );
}
