import * as React from "react";
import { Eye, EyeOff } from "lucide-react";

import { cn } from "./utils";

type PasswordInputProps = Omit<React.ComponentProps<"input">, "type">;

/** 与 input.tsx 一致的外框样式（边框在容器上，右侧为 suffix 插槽） */
const shellClass =
  "border-input bg-input-background flex h-9 w-full min-w-0 items-stretch overflow-hidden rounded-md border transition-[color,box-shadow] focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]";

const fieldClass =
  "placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground h-full min-w-0 flex-1 border-0 bg-transparent px-3 py-1 text-base outline-none disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm";

/** 隐藏浏览器自带的密码显示按钮 */
const nativeRevealHiddenClass =
  "[&::-ms-reveal]:hidden [&::-ms-clear]:hidden [&::-webkit-credentials-auto-fill-button]:hidden [&::-webkit-strong-password-auto-fill-button]:hidden";

function PasswordInput({ className, disabled, ...props }: PasswordInputProps) {
  const [visible, setVisible] = React.useState(false);

  return (
    <div className={cn(shellClass, className)} data-slot="password-input">
      <input
        type={visible ? "text" : "password"}
        data-slot="input"
        disabled={disabled}
        className={cn(fieldClass, nativeRevealHiddenClass)}
        {...props}
      />
      {/* suffix：固定在输入框内右侧 */}
      <button
        type="button"
        disabled={disabled}
        className="text-muted-foreground hover:text-foreground flex w-10 shrink-0 items-center justify-center self-center border-0 bg-transparent disabled:pointer-events-none disabled:opacity-50"
        onClick={() => setVisible((v) => !v)}
        aria-label={visible ? "Hide password" : "Show password"}
        aria-pressed={visible}
        tabIndex={0}
      >
        {visible ? (
          <EyeOff className="h-4 w-4 shrink-0" aria-hidden />
        ) : (
          <Eye className="h-4 w-4 shrink-0" aria-hidden />
        )}
      </button>
    </div>
  );
}

export { PasswordInput };
