import { useId, ComponentType } from 'react';

type ChildProps<Props> = Props & {
  id?: string;
};

export type WithIdProps<Props> = Props & {
  id: string;
};

/**
 * @internal
 * @param {ReactNode} WrappedComponent
 */
export default function withId<Props extends object>(
  WrappedComponent: ComponentType<WithIdProps<Props>>,
) {
  function WithIdComponent(props: ChildProps<Props>) {
    const id = useId();

    return <WrappedComponent {...props} id={props.id || id} />;
  }

  WithIdComponent.displayName = `withId(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;

  return WithIdComponent;
}
