"use client";
import React from "react";

import { Textarea } from "@/components/ui/textarea";
import { FormFieldWrapper } from "./FormFieldWrapper";
import { UseFormReturn, FieldPath, FieldValues } from "react-hook-form";

export interface TextAreaFieldProps<
  TFieldValues extends FieldValues = FieldValues,
  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> {
  form: UseFormReturn<TFieldValues>;
  name: TName;
  label?: string;
  placeholder?: string;
  description?: string;
  required?: boolean;
  disabled?: boolean;
  className?: string;
  rows?: number;
  maxLength?: number;
  showCharCount?: boolean;
}

export function TextAreaField<
  TFieldValues extends FieldValues = FieldValues,
  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
  form,
  name,
  label,
  placeholder,
  description,
  required = false,
  disabled = false,
  className,
  rows = 3,
  maxLength,
  showCharCount = false,
}: TextAreaFieldProps<TFieldValues, TName>) {
  const fieldValue = form.watch(name) as string;
  const charCount = fieldValue?.length || 0;

  return (
    <FormFieldWrapper
      form={form}
      name={name}
      label={label}
      description={
        showCharCount && maxLength
          ? `${description || ''} (${charCount}/${maxLength})`
          : description
      }
      required={required}
      className={className}
    >
      {(field) => (
        <Textarea
          placeholder={placeholder}
          disabled={disabled}
          rows={rows}
          maxLength={maxLength}
          {...field}
        />
      )}
    </FormFieldWrapper>
  );
}