import * as React from "react"
import { AlertCircle } from "lucide-react"
import { cn } from "@/lib/utils"

type LoginInputProps = React.ComponentProps<"input"> & {
  /** Visible label rendered above the field. */
  label?: string
  /** Error message shown below the field; also puts the field in its error state. */
  error?: string
  /** Error state without a message (e.g. when a message is shown elsewhere). */
  invalid?: boolean
  /** Icon rendered inside the field on the left. Omit for a plain input. */
  leftIcon?: React.ReactNode
  /** Element rendered inside the field on the right (e.g. a show/hide button). */
  rightElement?: React.ReactNode
  /** Classes for the outer wrapper (label + field + error). */
  containerClassName?: string
}

function LoginInput({
  id,
  label,
  error,
  invalid,
  leftIcon,
  rightElement,
  className,
  containerClassName,
  disabled,
  ...props
}: LoginInputProps) {
  const autoId = React.useId()
  const inputId = id ?? autoId
  const errorId = `${inputId}-error`
  const message = error?.trim()
  const hasError = invalid || !!error

  return (
    <div className={containerClassName}>
      {label && (
        <label htmlFor={inputId} className="mb-2 block text-base font-medium">
          {label}
        </label>
      )}
      <div className="relative">
        {leftIcon && (
          <span className="pointer-events-none absolute top-1/2 left-4 flex -translate-y-1/2 items-center">
            {leftIcon}
          </span>
        )}
        <input
          id={inputId}
          disabled={disabled}
          aria-invalid={hasError}
          aria-describedby={message ? errorId : undefined}
          className={cn(
            "w-full rounded-lg border bg-bg-surface py-3.5 text-base placeholder-text-placeholder transition focus:ring-2 focus:outline-none disabled:cursor-not-allowed disabled:bg-bg-input disabled:opacity-70",
            leftIcon ? "pl-12" : "pl-4",
            rightElement ? "pr-12" : "pr-4",
            hasError
              ? "border-state-error focus:border-state-error focus:ring-state-error/20"
              : "border-border-subtle hover:border-border-hover focus:border-brand-primary focus:ring-brand-primary/20",
            className
          )}
          {...props}
        />
        {rightElement && (
          <span className="absolute top-1/2 right-1 flex -translate-y-1/2 items-center">
            {rightElement}
          </span>
        )}
      </div>
      {message && (
        <p
          id={errorId}
          role="alert"
          className="mt-1.5 flex items-center gap-1.5 text-sm text-state-error"
        >
          <AlertCircle className="size-4 shrink-0" />
          {message}
        </p>
      )}
    </div>
  )
}

export { LoginInput }
export type { LoginInputProps }
