"use client";

import React, { useId, useState } from "react";
import { AlertCircle, Eye, EyeOff } from "lucide-react";
import type { LucideIcon } from "lucide-react";

interface AuthFieldProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "id" | "className"> {
  label: string;
  icon: LucideIcon;
  /** Inline validation message; presence switches the field into its error state. */
  error?: string | null;
  /** Optional node rendered right of the label — e.g. a "forgot password" link. */
  trailingLabel?: React.ReactNode;
  /** Localised caps-lock hint. Only rendered for password fields. */
  capsLockHint?: string;
}

/**
 * Single input row: caps label, leading icon, error state, and — for passwords —
 * a reveal toggle plus caps-lock detection.
 *
 * The focus ring is drawn with an inset box-shadow rather than a thicker border
 * so the 2px "locked" state of the design system never shifts layout.
 */
export function AuthField({
  label,
  icon: Icon,
  error,
  trailingLabel,
  capsLockHint,
  type = "text",
  ...inputProps
}: AuthFieldProps) {
  const reactId = useId();
  const inputId = `field-${reactId}`;
  const errorId = `${inputId}-error`;
  const capsId = `${inputId}-caps`;

  const isPassword = type === "password";
  const [revealed, setRevealed] = useState(false);
  const [capsLockOn, setCapsLockOn] = useState(false);

  const showCapsWarning = isPassword && capsLockOn && !!capsLockHint;

  const describedBy = [error ? errorId : null, showCapsWarning ? capsId : null]
    .filter(Boolean)
    .join(" ");

  const handleCapsProbe = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (!isPassword) return;
    setCapsLockOn(event.getModifierState?.("CapsLock") ?? false);
  };

  return (
    <div>
      <div className="flex items-baseline justify-between gap-3 mb-1.5">
        <label
          htmlFor={inputId}
          className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] font-medium"
        >
          {label}
        </label>
        {trailingLabel}
      </div>

      <div className="relative">
        <Icon
          aria-hidden="true"
          className={`absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 transition-colors ${
            error ? "text-[#BA1A1A]" : "text-[#94A3B8]"
          }`}
        />
        <input
          {...inputProps}
          id={inputId}
          type={isPassword && revealed ? "text" : type}
          aria-invalid={error ? true : undefined}
          aria-describedby={describedBy || undefined}
          onKeyUp={handleCapsProbe}
          onKeyDown={handleCapsProbe}
          onBlur={(event) => {
            setCapsLockOn(false);
            inputProps.onBlur?.(event);
          }}
          className={`w-full h-12 pl-11 ${
            isPassword ? "pr-12" : "pr-3.5"
          } bg-white border text-[15px] text-black font-sans placeholder:text-[#94A3B8] transition-[border-color,box-shadow] duration-150 focus:outline-none ${
            error
              ? "border-[#BA1A1A] focus:shadow-[inset_0_0_0_1px_#BA1A1A]"
              : "border-[#E2E8F0] hover:border-[#C4C7C9] focus:border-black focus:shadow-[inset_0_0_0_1px_#000000]"
          }`}
        />

        {isPassword && (
          <button
            type="button"
            onClick={() => setRevealed((current) => !current)}
            aria-label={revealed ? "Hide password" : "Show password"}
            aria-pressed={revealed}
            className="absolute right-0 top-0 h-12 w-12 flex items-center justify-center text-[#94A3B8] hover:text-black transition-colors"
          >
            {revealed ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
          </button>
        )}
      </div>

      {error && (
        <p
          id={errorId}
          role="alert"
          className="flex items-start gap-1.5 mt-1.5 text-[12px] text-[#BA1A1A] leading-snug"
        >
          <AlertCircle className="w-3.5 h-3.5 shrink-0 mt-px" aria-hidden="true" />
          <span>{error}</span>
        </p>
      )}

      {showCapsWarning && (
        <p
          id={capsId}
          className="mt-1.5 font-mono text-[11px] uppercase tracking-wider text-[#B45309]"
        >
          {capsLockHint}
        </p>
      )}
    </div>
  );
}
