"use client";

import cx from "classnames";
import React, { ReactNode } from "react";

import { Messages } from "../Field/Messages";

import { FieldsetContext } from "./FieldsetContext";

export interface FieldsetMessage {
  [key: string]: any;
}

export interface FieldsetProps
  extends React.FieldsetHTMLAttributes<HTMLFieldSetElement> {
  /** Required `<legend />` for fieldset */
  legend: ReactNode;
  /** Additional legend props */
  legendProps?: React.HTMLAttributes<HTMLLegendElement>;
  description?: ReactNode;
  messages?: FieldsetMessage[];
  className?: string;
  children?: ReactNode;
}

const CLASS_ROOT = "fieldset";

const Fieldset: React.FC<FieldsetProps> = ({
  legend,
  legendProps,
  description,
  className,
  children,
  messages,
  ...other
}) => {
  const classes = cx(CLASS_ROOT, className);

  return (
    <fieldset className={classes} {...other}>
      <legend {...legendProps}>{legend}</legend>
      {description}
      {messages ? (
        <FieldsetContext.Provider
          value={{
            // @ts-expect-error wrong type declarations
            messages,
          }}
        >
          <Messages isMain />

          {children}
          <Messages />
        </FieldsetContext.Provider>
      ) : (
        children
      )}
    </fieldset>
  );
};

Fieldset.displayName = "Fieldset";

export { Fieldset };
