"use client";

import React, { ReactNode } from "react";
import {
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormDescription,
  FormMessage,
} from "@/components/ui/form";
import { UseFormReturn, FieldPath, FieldValues } from "react-hook-form";

export interface FormFieldWrapperProps<
  TFieldValues extends FieldValues = FieldValues,
  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> {
  form: UseFormReturn<TFieldValues>;
  name: TName;
  label?: string;
  description?: string;
  required?: boolean;
  children: ReactNode | ((field: any) => ReactNode);
  className?: string;
  /**
   * If true, the FormControl wrapper will be omitted.
   * Useful when the child component handles FormControl internally (e.g. for complex layouts).
   */
  skipFormControl?: boolean;
}

export function FormFieldWrapper<
  TFieldValues extends FieldValues = FieldValues,
  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
  form,
  name,
  label,
  description,
  required = false,
  children,
  className,
  skipFormControl = false,
}: FormFieldWrapperProps<TFieldValues, TName>) {
  return (
    <FormField
      control={form.control}
      name={name}
      render={({ field }) => (
        <FormItem className={className}>
          {label && (
            <FormLabel>
              {label}
              {required && <span className="text-destructive ml-1">*</span>}
            </FormLabel>
          )}

          {skipFormControl ? (
            typeof children === 'function' ? children(field) : children
          ) : (
            <FormControl>
              {typeof children === 'function' ? children(field) : children}
            </FormControl>
          )}

          {description && <FormDescription>{description}</FormDescription>}
          <FormMessage />
        </FormItem>
      )}
    />
  );
}
