import {
  type CSSProperties,
  type ReactNode,
  isValidElement,
  cloneElement,
  useId,
} from "react";

interface FormFieldProps {
  label: ReactNode;
  children: ReactNode;
  error?: string;
  required?: boolean;
  style?: React.CSSProperties;
}

export default function FormField({
  label,
  children,
  error,
  required,
  style,
}: FormFieldProps) {
  const generatedId = useId();
  const childProps = isValidElement(children)
    ? (children.props as Record<string, unknown>)
    : null;
  const childId = childProps?.id ? String(childProps.id) : generatedId;
  const childWithId = isValidElement(children)
    ? cloneElement(children, { id: childId } as React.Attributes)
    : children;

  return (
    <div className="admin-form-group" style={style}>
      <label className="admin-form-label" htmlFor={childId}>
        {label}
        {required && <span className="admin-form-required"> *</span>}
      </label>
      {childWithId}
      {error && <span className="admin-form-error">{error}</span>}
    </div>
  );
}
