import VisibilityIcon from "@mui/icons-material/Visibility";
import VisibilityOffIcon from "@mui/icons-material/VisibilityOff";
import {
  FormControl,
  FormHelperText,
  IconButton,
  InputAdornment,
  InputLabel,
  OutlinedInput,
} from "@mui/material";
import React from "react";
import { ServerApi } from "../api/ServerApi";

export function PasswordInput(p: {
  value: string;
  onChange: (newPassword: string) => void;
  label: string;
}) {
  const [showPassword, setShowPassword] = React.useState(false);

  const error = p.value.length > 0 ? ServerApi.CheckPassword(p.value) : null;
  const handleClickShowPassword = () => setShowPassword((show) => !show);

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

  return (
    <FormControl fullWidth variant="outlined">
      <InputLabel htmlFor="pwdinput" error={error !== null}>
        {p.label}
      </InputLabel>
      <OutlinedInput
        id="pwdinput"
        required
        error={error !== null}
        value={p.value}
        label={p.label}
        type={showPassword ? "text" : "password"}
        fullWidth
        onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
          p.onChange(event.target.value);
        }}
        endAdornment={
          <InputAdornment position="end">
            <IconButton
              aria-label="toggle password visibility"
              onClick={handleClickShowPassword}
              onMouseDown={handleMouseDownPassword}
              edge="end"
            >
              {showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
            </IconButton>
          </InputAdornment>
        }
      />

      <FormHelperText error id="pwd-helper-text">
        {error !== null ? error : ""}
      </FormHelperText>
    </FormControl>
  );
}
