"use client";

import { forwardRef, InputHTMLAttributes, useState } from "react";
import { Eye, EyeOff, LucideIcon } from "lucide-react";
import { cn } from "@/lib/cn";

interface AuthTextFieldProps extends InputHTMLAttributes<HTMLInputElement> {
  label: string;
  icon?: LucideIcon;
  error?: string;
}

export const AuthTextField = forwardRef<HTMLInputElement, AuthTextFieldProps>(
  ({ label, icon: Icon, error, type, className, ...props }, ref) => {
    const [show, setShow] = useState(false);
    const isPassword = type === "password";

    return (
      <div className={className}>
        <label className="mb-1.5 block text-xs font-medium text-paper/70">{label}</label>
        <div
          className={cn(
            "flex items-center gap-2.5 rounded-xl border px-3.5 py-2.5 transition-colors",
            error
              ? "border-danger/60 bg-danger/5"
              : "border-white/10 bg-white/[0.06] focus-within:border-gold/50"
          )}
        >
          {Icon && <Icon size={15} className="shrink-0 text-paper/40" strokeWidth={2} />}
          <input
            ref={ref}
            type={isPassword && show ? "text" : type}
            className="w-full bg-transparent text-sm text-paper outline-none placeholder:text-paper/30"
            {...props}
          />
          {isPassword && (
            <button
              type="button"
              onClick={() => setShow((s) => !s)}
              className="shrink-0 text-paper/40"
              tabIndex={-1}
            >
              {show ? <EyeOff size={15} /> : <Eye size={15} />}
            </button>
          )}
        </div>
        {error && <p className="mt-1.5 text-xs text-danger">{error}</p>}
      </div>
    );
  }
);

AuthTextField.displayName = "AuthTextField";
