"use client"

import * as React from "react"
import {
  type Control,
  type FieldPath,
  type FieldValues,
} from "react-hook-form"

import {
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/components/ui/form"
import { Textarea } from "@/shared/components/ui/textarea"

export interface TextareaFieldProps<
  TFieldValues extends FieldValues = FieldValues,
  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> {
  /** react-hook-form control 实例 */
  control: Control<TFieldValues>
  /** 字段路径 */
  name: TName
  /** 标签文本 */
  label: string
  /** 占位符 */
  placeholder?: string
  /** 描述文本 */
  description?: React.ReactNode
  /** 是否禁用 */
  disabled?: boolean
  /** FormItem 的 className */
  itemClassName?: string
  /** Textarea 的额外 className（如 "min-h-[200px]"） */
  textareaClassName?: string
  /** 透传到 Textarea 的其他 props（如 rows、maxLength） */
  textareaProps?: Omit<
    React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    "name" | "value" | "onChange" | "onBlur" | "disabled" | "placeholder" | "className"
  >
}

/**
 * 通用多行文本字段组件，封装 FormField + FormItem + FormLabel + FormControl + Textarea + FormMessage。
 *
 * 用于替代各表单中重复的 `<FormField render={({ field }) => <Textarea {...field} />}>` 模式。
 *
 * @example
 * <TextareaField
 *   control={control}
 *   name="content"
 *   label="Content"
 *   placeholder="Enter text..."
 *   textareaClassName="min-h-[100px]"
 * />
 */
export function TextareaField<
  TFieldValues extends FieldValues = FieldValues,
  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
  control,
  name,
  label,
  placeholder,
  description,
  disabled,
  itemClassName,
  textareaClassName,
  textareaProps,
}: TextareaFieldProps<TFieldValues, TName>) {
  return (
    <FormField
      control={control}
      name={name}
      render={({ field }) => (
        <FormItem className={itemClassName}>
          <FormLabel>{label}</FormLabel>
          <FormControl>
            <Textarea
              placeholder={placeholder}
              disabled={disabled}
              className={textareaClassName}
              {...textareaProps}
              {...field}
            />
          </FormControl>
          {description ? <FormDescription>{description}</FormDescription> : null}
          <FormMessage />
        </FormItem>
      )}
    />
  )
}
