import React from "react";

import { LoadingButton } from "@mui/lab";
import { FormControl, FormGroup, Stack, TextField, Typography } from "@mui/material";

import { useSnackbar } from "notistack";

import { useI18n } from "../../../contexts/I18nContext";
import { useUser } from "../../../contexts/UserContext";

export interface PasswordChangeFields {
  "Old password": string;
  Password: string;
  "Password (again)": string;
}

const PasswordChangeForm: React.FC = () => {
  const { t } = useI18n();
  const { enqueueSnackbar } = useSnackbar();
  const [loading, setLoading] = React.useState(false);

  const [fields, setFields] = React.useState<PasswordChangeFields>({
    "Old password": "",
    Password: "",
    "Password (again)": "",
  });

  const { changePassword } = useUser();

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

    try {
      await changePassword(fields["Old password"], fields["Password"], fields["Password (again)"]);

      enqueueSnackbar(t("Password changed successfully."), {
        variant: "success",
      });

      setFields({
        "Old password": "",
        Password: "",
        "Password (again)": "",
      });
    } catch {
      enqueueSnackbar(t("Incorrect authentication credentials."), {
        variant: "error",
      });
    } finally {
      setLoading(false);
    }
  };

  const onChange = (event: React.ChangeEvent<{ name: string; value: string }>) => {
    setFields({
      ...fields,
      [event.target.name]: event.target.value,
    });
  };

  return (
    <Stack
      component="form"
      data-testid="change-password-form"
      gap={2}
      sx={{ maxWidth: 350 }}
      onSubmit={onSubmit}
    >
      <Typography color="grey.600" variant="body2">
        {t(
          "Please enter your old password, for security’s sake, and then enter your new password twice so we can verify you typed it in correctly.",
        )}
      </Typography>

      <FormControl fullWidth component="fieldset">
        <FormGroup>
          {(["Old password", "Password", "Password (again)"] as const).map((field) => (
            <TextField
              key={field}
              fullWidth
              required
              autoComplete={field}
              color="secondary"
              label={t(field)}
              name={field}
              sx={{ mt: 1.5 }}
              type="password"
              value={fields[field]}
              onChange={onChange}
            />
          ))}
        </FormGroup>
      </FormControl>

      <LoadingButton fullWidth color="primary" loading={loading} type="submit" variant="contained">
        {t("Change my password")}
      </LoadingButton>
    </Stack>
  );
};

export default PasswordChangeForm;
