"use client";

import React from "react";
import { FieldsetContext } from "../Fieldset/FieldsetContext";
import { Message } from "../Message";
import type { MessageType as MessageTypeEnum } from "../Message/Message";
import { FieldContext } from "./FieldContext";

export interface MessageType {
  isMain: boolean;
  type: MessageTypeEnum;
  text: React.ReactNode;
}

export interface MessagesProps {
  isMain?: boolean;
}

const Messages: React.FC<MessagesProps> = ({ isMain }) => {
  const fieldContext = React.useContext(FieldContext);
  const fieldsetContext = React.useContext(FieldsetContext);
  const { controlId, messages = [] } = fieldContext ?? fieldsetContext ?? {};
  return (messages as MessageType[])
    .filter((m) => isMain === m.isMain)
    .map((message, index) => (
      <Message
        id={`${controlId}-message-${index}`}
        key={index.toString()}
        type={message.type}
      >
        {message.text}
      </Message>
    ));
};

export { Messages };
