import { forwardRef, cloneElement, isValidElement, useId } from "react";
import { cn } from "@/lib/utils";
import { Label, type LabelProps } from "@/components/atoms/label";
import { Input, type InputProps } from "@/components/atoms/input";
import { ErrorMessage } from "@/components/atoms/error-message";

interface FormFieldProps
  extends Omit<
    InputProps,
    "id" | "aria-describedby" | "aria-invalid" | "children" | "dangerouslySetInnerHTML"
  > {
  label?: string;
  error?: string;
  helperText?: string;
  required?: boolean;
  labelProps?: Omit<LabelProps, "htmlFor">;
  fieldId?: string;
  children?: React.ReactNode;
  containerClassName?: string;
  inputClassName?: string;
}

const FormField = forwardRef<HTMLInputElement, FormFieldProps>(
  (
    {
      label,
      error,
      helperText,
      required,
      labelProps,
      fieldId,
      containerClassName,
      inputClassName,
      children,
      ...inputProps
    },
    ref
  ) => {
    const generatedId = useId();
    const id = fieldId || generatedId;
    const errorId = error ? `${id}-error` : undefined;
    const helperTextId = helperText ? `${id}-helper` : undefined;

    const { className: inputPropsClassName, ...restInputProps } = inputProps;

    return (
      <div className={cn("space-y-1", containerClassName)}>
        {label && (
          <Label
            htmlFor={id}
            className={cn(
              "block text-sm font-medium text-gray-700",
              error && "text-red-600",
              labelProps?.className
            )}
            {...(labelProps ? { ...labelProps, className: undefined } : undefined)}
          >
            <span>{label}</span>
            {required ? (
              <span aria-hidden="true" className="ml-1 text-red-600">
                *
              </span>
            ) : null}
          </Label>
        )}
        {children ? (
          isValidElement(children) ? (
            cloneElement(children, {
              id,
              "aria-invalid": error ? "true" : undefined,
              "aria-describedby": cn(errorId, helperTextId) || undefined,
            } as Record<string, unknown>)
          ) : (
            children
          )
        ) : (
          <Input
            id={id}
            ref={ref}
            aria-invalid={error ? "true" : undefined}
            aria-describedby={cn(errorId, helperTextId) || undefined}
            className={cn(
              error && "border-red-500 focus-visible:ring-red-500 focus-visible:ring-offset-2",
              inputClassName,
              inputPropsClassName
            )}
            {...restInputProps}
          />
        )}
        {error && <ErrorMessage id={errorId}>{error}</ErrorMessage>}
        {helperText && !error && (
          <p id={helperTextId} className="text-sm text-gray-500">
            {helperText}
          </p>
        )}
      </div>
    );
  }
);
FormField.displayName = "FormField";

export { FormField };
export type { FormFieldProps };
