// src/components/auth/PasswordField.jsx
import React, { useState } from "react";
import PasswordRulesTooltip from "./PasswordRulesTooltip";
import PasswordStrengthBar from "./PasswordStrengthBar";
import { TbEye, TbEyeOff } from "react-icons/tb";

export default function PasswordField({
  label = "رمز عبور",
  reg, // ✅ خروجی register("password")
  showTip,
  setShowTip,
  rules,
  strength,
  errorText,
  wrapperRef,

  // ✅ اختیاری: اگر خواستی کنترلش از بیرون باشه
  show,
  setShow,
  disabled = false,
}) {
  const [localShow, setLocalShow] = useState(false);

  const isControlled = typeof show === "boolean" && typeof setShow === "function";
  const isShow = isControlled ? show : localShow;
  const toggleShow = () => (isControlled ? setShow((s) => !s) : setLocalShow((s) => !s));

  return (
    <>
      <div
        ref={wrapperRef}
        className="w-full mt-6 text-white bg-[#A1E3F919] rounded-md grid relative items-center"
      >
        {/* 👁️ چشم اول اینپوت (RTL => سمت راست) */}
        <button
          type="button"
          onClick={toggleShow}
          disabled={disabled}
          aria-label="toggle password"
          className="absolute inset-y-0 end-3 my-auto h-10 w-10 grid place-items-center rounded-lg hover:bg-black/5 dark:hover:bg-white/10 transition disabled:opacity-60"
          onMouseDown={(e) => e.preventDefault()} // جلوگیری از از دست رفتن فوکوس اینپوت
        >
          {isShow ? <TbEyeOff className="w-5 h-5" /> : <TbEye className="w-5 h-5" />}
        </button>

        <input
          className="peer h-14 px-6 w-full outline-0 focus:outline-0 text-white rounded-md placeholder:hidden bg-transparent pe-14"
          placeholder=" "
          type={isShow ? "text" : "password"}
          disabled={disabled}
          {...reg}
          onFocus={(e) => {
            reg.onFocus?.(e);
            setShowTip(true);
          }}
          onBlur={(e) => {
            reg.onBlur?.(e);
            setTimeout(() => setShowTip(false), 120);
          }}
          onChange={(e) => {
            // ✅ خیلی مهم: RHF باید خبر دار بشه تا watch کار کنه
            reg.onChange(e);
            if (!showTip) setShowTip(true);
          }}
        />

        <label className="absolute px-6 duration-200 text-md font-medium pointer-events-none peer-not-placeholder-shown:text-sm peer-not-placeholder-shown:px-3 peer-not-placeholder-shown:-translate-y-8 peer-focus:text-sm peer-focus:px-3 peer-focus:-translate-y-8">
          {label}
        </label>

        <PasswordRulesTooltip
          open={showTip}
          rules={rules}
          onPointerDown={(e) => e.stopPropagation()}
        />
      </div>

      <PasswordStrengthBar strength={strength} />

      {errorText && (
        <span className="text-red-600 font-bold text-sm mt-2 block">
          {errorText}
        </span>
      )}
    </>
  );
}
