"use client";

import { Controller, type Control, type FieldPath, type FieldValues } from "react-hook-form";

import { formFieldClass, formInputClass } from "@/components/form/common/form-layout";
import { Field, FieldError, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";

type TextFieldProps<T extends FieldValues> = {
  control: Control<T>;
  name: FieldPath<T>;
  label: string;
  placeholder?: string;
  autoComplete?: string;
  className?: string;
  inputClassName?: string;
  readOnly?: boolean;
};

export function TextField<T extends FieldValues>({
  control,
  name,
  label,
  placeholder,
  autoComplete,
  className,
  inputClassName,
  readOnly = false,
}: TextFieldProps<T>) {
  return (
    <Controller
      control={control}
      name={name}
      render={({ field, fieldState }) => (
        <Field className={cn(formFieldClass, className)} data-invalid={!!fieldState.error}>
          <FieldLabel htmlFor={String(name)}>{label}</FieldLabel>
          <Input
            {...field}
            id={String(name)}
            placeholder={placeholder}
            autoComplete={autoComplete}
            value={field.value ?? ""}
            readOnly={readOnly}
            aria-invalid={!!fieldState.error}
            className={cn(formInputClass, readOnly && "bg-muted/40 text-foreground", inputClassName)}
          />
          {fieldState.error ? <FieldError errors={[fieldState.error]} /> : null}
        </Field>
      )}
    />
  );
}
