"use client";

import classNames from "classnames/dedupe";
import { useRef, useState } from "react";
import { mergeRefs } from "../../utils/mergeRefs";
import {
  TextField,
  type TextFieldElementType,
  type TextFieldProps,
} from "../TextField";
import { ShowHideButton } from "./ShowHideButton";
import "./PasswordField.css";

export type PasswordFieldAutoComplete = "current-password" | "new-password";

export interface PasswordFieldProps extends TextFieldProps {
  autoComplete?: PasswordFieldAutoComplete;
}

export const PasswordField = ({
  ref,
  className,
  autoComplete = "current-password",
  ...props
}: PasswordFieldProps) => {
  const [show, setShow] = useState(false);
  const type = show ? "text" : "password";
  const classes = classNames("mobius-password-field", className);
  const localRef = useRef<TextFieldElementType>(null);

  const handleShowHideButtonClick = () => {
    const selectionStart = localRef.current?.selectionStart;
    const selectionEnd = localRef.current?.selectionEnd;

    setShow(oldShow => !oldShow);
    requestAnimationFrame(() => {
      localRef.current?.focus();
      if (selectionStart != null && selectionEnd != null) {
        localRef.current?.setSelectionRange(selectionStart, selectionEnd);
      }
    });
  };

  return (
    <TextField
      ref={mergeRefs([localRef, ref])}
      className={classes}
      {...props}
      autoComplete={autoComplete}
      type={type}
      suffixInside={
        <ShowHideButton onClick={handleShowHideButtonClick} show={show} />
      }
    />
  );
};

PasswordField.displayName = "PasswordField";
