"use client";

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

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

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

    return (
      <div className={className}>
        <label className="mb-2 block text-sm font-medium text-paper/70">{label}</label>
        <div
          className={cn(
            "flex items-center gap-3 rounded-2xl border px-4 py-3.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={17} className="shrink-0 text-paper/40" strokeWidth={2} />}
          <input
            ref={ref}
            type={isPassword && show ? "text" : type}
            className="w-full bg-transparent text-[15px] 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={17} /> : <Eye size={17} />}
            </button>
          )}
        </div>
        {error && <p className="mt-1.5 text-xs text-danger">{error}</p>}
      </div>
    );
  }
);

TextField.displayName = "TextField";
