"use client";

import React, { InputHTMLAttributes, useId } from "react";
import { AlertCircle } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";

interface TextBoxProps extends InputHTMLAttributes<HTMLInputElement> {
  label?: string;
  error?: string;
  containerClass?: string;
  inputClass?: string;
  type?: string;
  fullHeight?: boolean;
}

/**
 * Labelled text field used across every transaction form.
 *
 * Now composed from the shadcn `Input` and `Label` primitives rather than a
 * bespoke input. What this still owns is the label/error/description wiring.
 *
 * Two accessibility fixes carried over: the label is genuinely associated with
 * the control (it was a floating `<label>` with no `htmlFor`, so clicking it
 * did nothing and screen readers announced the field unlabelled), and the error
 * is linked with `aria-describedby` and announced via `role="alert"`.
 *
 * The prop shape is unchanged, so all existing call sites keep working.
 */
export const TextBox: React.FC<TextBoxProps> = ({
  label,
  error,
  containerClass = "",
  inputClass = "",
  type = "text",
  className,
  fullHeight = false,
  placeholder,
  id,
  ...rest
}) => {
  const generatedId = useId();
  const inputId = id ?? generatedId;
  const errorId = `${inputId}-error`;

  const isDateInput = type === "date";
  const resolvedPlaceholder = placeholder ?? (isDateInput ? "YYYY-MM-DD" : undefined);

  return (
    <div className={cn("flex flex-col gap-2", containerClass)}>
      {label && (
        <Label htmlFor={inputId} className="text-xs text-muted-foreground">
          {label}
        </Label>
      )}

      <Input
        id={inputId}
        type={type}
        placeholder={resolvedPlaceholder}
        autoComplete="off"
        aria-invalid={Boolean(error)}
        aria-describedby={error ? errorId : undefined}
        className={cn(fullHeight && "h-10", inputClass, className)}
        {...rest}
      />

      {error && (
        <p
          id={errorId}
          role="alert"
          className="flex items-center gap-1 text-xs font-medium text-destructive"
        >
          <AlertCircle className="size-3 shrink-0" aria-hidden />
          {error}
        </p>
      )}
    </div>
  );
};
