"use client";

import classNames from "classnames/dedupe";
import type { ReactElement, ReactNode, RefAttributes } from "react";
import { cloneElement, useId } from "react";
import type { DOMProps } from "../../types/dom";
import { Flex } from "../Flex";
import "./Fieldset.css";

export type LegendProps = {
  id?: string;
  className?: string;
};

type ContainerProps = {
  "aria-labelledby"?: string;
  role: string;
};

const useFieldset = (
  props: FieldsetProps,
): { legendProps: LegendProps; containerProps: ContainerProps } => {
  const { legend } = props;

  let legendProps: LegendProps = {};
  let containerProps: ContainerProps = {
    role: "group",
  };

  const legendId = useId();
  if (legend) {
    legendProps = {
      ...legendProps,
      id: legendId,
    };
    containerProps = {
      ...containerProps,
      "aria-labelledby": legendId,
    };
  }

  return {
    legendProps,
    containerProps,
  };
};

export type FieldsetElementType = HTMLDivElement;
export interface FieldsetProps
  extends DOMProps, RefAttributes<FieldsetElementType> {
  legend?: string;
  children: ReactNode;
  className?: string;
  legendComponent?: ReactElement;
}

const Fieldset = ({ ref: _ref, ...props }: FieldsetProps) => {
  const {
    children,
    legend,
    legendComponent = <legend />,
    ...otherProps
  } = props;

  const { legendProps, containerProps } = useFieldset(props);

  const classes = classNames("mobius", "mobius-fieldset", props.className);

  // Set class on legend
  legendProps.className = "mobius-fieldset__legend";

  return (
    <Flex {...containerProps} {...otherProps} className={classes}>
      {legend && cloneElement(legendComponent, { ...legendProps }, [legend])}
      {children}
    </Flex>
  );
};

Fieldset.displayName = "Fieldset";
export { Fieldset };
