"use client";

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

import { formFieldClass, formRemarkTextareaClass } from "@/components/form/common/form-layout";
import { Field, FieldError, FieldLabel } from "@/components/ui/field";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";

type TextAreaFieldProps<T extends FieldValues> = {
  control: Control<T>;
  name: FieldPath<T>;
  label: string;
  placeholder?: string;
  rows?: number;
  className?: string;
  readOnly?: boolean;
};

export function TextAreaField<T extends FieldValues>({
  control,
  name,
  label,
  placeholder,
  rows = 3,
  className,
  readOnly = false,
}: TextAreaFieldProps<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>
          <Textarea
            {...field}
            id={String(name)}
            rows={rows}
            placeholder={placeholder}
            value={field.value ?? ""}
            readOnly={readOnly}
            aria-invalid={!!fieldState.error}
            className={cn(formRemarkTextareaClass, readOnly && "bg-muted/40")}
          />
          {fieldState.error ? <FieldError errors={[fieldState.error]} /> : null}
        </Field>
      )}
    />
  );
}
