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

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 ? <VisibilityOff /> : <Visibility />}
            </IconButton>
          </InputAdornment>
        }
      />

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