import React from "react";
import generateId from "../../../utils/generateId";

interface Message {
  // Define the structure of a message if known, otherwise use any
  [key: string]: any;
}

export const getDescribedBy = (
  hint: string | undefined | React.ReactNode,
  messages: Message[],
  tooltip: string | undefined | React.ReactNode,
  id: string,
): string =>
  [
    ...(hint ? [`${id}-hint`] : []), // this spread ensures we don't add an undefined array item
    ...messages.map((_, i) => `${id}-message-${i}`),
    ...(tooltip ? [`${id}-tooltip`] : []),
  ].join(" ");

interface InnerControl {
  id?: string;
  [key: string]: any;
}

interface Control {
  id?: string;
  control?: InnerControl;
  [key: string]: any;
}

export const getControlId = (control: Control): string => {
  const { id, control: innerControl } = control;

  return id ?? (innerControl && innerControl.id) ?? generateId();
};
