"use client";

import { useState, InputHTMLAttributes, forwardRef } from "react";
import { Eye, EyeOff } from "lucide-react";

interface AuthFieldProps extends InputHTMLAttributes<HTMLInputElement> {
  label: string;
  error?: string;
  isPassword?: boolean;
}

export const AuthField = forwardRef<HTMLInputElement, AuthFieldProps>(
  ({ label, error, isPassword, type, className, ...props }, ref) => {
    const [show, setShow] = useState(false);
    const inputType = isPassword ? (show ? "text" : "password") : type;

    return (
      <div className="flex flex-col gap-1.5">
        <label className="text-xs font-semibold tracking-wide uppercase" style={{ color: "var(--text-muted)" }}>
          {label}
        </label>
        <div className="relative">
          <input
            ref={ref}
            type={inputType}
            className="w-full rounded-xl px-4 py-3 text-sm outline-none transition-all duration-150 pr-10"
            style={{
              background: "var(--deep)",
              border: `1.5px solid ${error ? "#ef4444" : "var(--border)"}`,
              color: "var(--text-primary)",
              caretColor: "var(--accent)",
            }}
            onFocus={(e) => {
              e.currentTarget.style.borderColor = error ? "#ef4444" : "var(--accent)";
              e.currentTarget.style.boxShadow = error
                ? "0 0 0 3px rgba(239,68,68,0.12)"
                : "0 0 0 3px rgba(var(--accent-rgb),0.12)";
            }}
            onBlur={(e) => {
              e.currentTarget.style.borderColor = error ? "#ef4444" : "var(--border)";
              e.currentTarget.style.boxShadow = "none";
            }}
            {...props}
          />
          {isPassword && (
            <button
              type="button"
              tabIndex={-1}
              onClick={() => setShow((s) => !s)}
              className="absolute right-3 top-1/2 -translate-y-1/2 transition-opacity hover:opacity-80"
              style={{ color: "var(--text-muted)" }}
            >
              {show ? <EyeOff size={16} /> : <Eye size={16} />}
            </button>
          )}
        </div>
        {error && (
          <p className="text-xs" style={{ color: "#ef4444" }}>
            {error}
          </p>
        )}
      </div>
    );
  },
);
AuthField.displayName = "AuthField";
