import useOnClickOutside from '@utils/hooks/use-on-click-outside';
import {
  cloneElement,
  FC,
  ReactComponentElement,
  ReactNode,
  useRef,
  useState,
} from 'react';
import HelpButton from '../buttons/help-button';
import Tooltip from '../modals/tooltip';
import styles from './fieldset.module.scss';

export type FieldsetProps = {
  /**
   * Set additional classnames to the body wrapper.
   */
  bodyClassName?: string;
  /**
   * Set additional classnames to the help button.
   */
  buttonClassName?: string;
  /**
   * The fieldset body.
   */
  children: ReactNode | ReactNode[];
  /**
   * Set additional classnames to the fieldset wrapper.
   */
  className?: string;
  /**
   * The fieldset legend.
   */
  legend: string;
  /**
   * Set additional classnames to the legend.
   */
  legendClassName?: string;
  /**
   * The legend position.
   *
   * @default 'stacked'
   */
  legendPosition?: 'inline' | 'stacked';
  /**
   * An accessible role.
   *
   * @default 'group'
   */
  role?: 'group' | 'radiogroup' | 'presentation' | 'none';
  /**
   * An optional tooltip component.
   */
  Tooltip?: ReactComponentElement<typeof Tooltip>;
};

/**
 * Fieldset component
 *
 * Render a fieldset with a legend.
 */
const Fieldset: FC<FieldsetProps> = ({
  bodyClassName = '',
  buttonClassName = '',
  children,
  className = '',
  legend,
  legendClassName = '',
  legendPosition = 'stacked',
  Tooltip: TooltipComponent,
  ...props
}) => {
  const [isTooltipOpened, setIsTooltipOpened] = useState<boolean>(false);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const wrapperModifier = `wrapper--${legendPosition}`;
  const buttonModifier = isTooltipOpened ? styles['btn--activated'] : '';
  const legendModifier =
    TooltipComponent === undefined ? '' : 'legend--has-tooltip';
  const tooltipModifier = isTooltipOpened
    ? 'tooltip--visible'
    : 'tooltip--hidden';

  /**
   * Close the tooltip if the target is not the button.
   *
   * @param {Node} target - The event target.
   */
  const closeTooltip = (target: Node) => {
    if (buttonRef.current && !buttonRef.current.contains(target)) {
      setIsTooltipOpened(false);
    }
  };

  const tooltipRef = useOnClickOutside<HTMLDivElement>(closeTooltip);

  return (
    <fieldset
      className={`${styles.wrapper} ${styles[wrapperModifier]} ${className}`}
      {...props}
    >
      <legend
        className={`${styles.legend} ${styles[legendModifier]} ${legendClassName}`}
      >
        {legend}
      </legend>
      {TooltipComponent && (
        <>
          <HelpButton
            aria-pressed={isTooltipOpened}
            className={`${styles.btn} ${buttonModifier} ${buttonClassName}`}
            onClick={() => setIsTooltipOpened(!isTooltipOpened)}
            ref={buttonRef}
          />
          {cloneElement(TooltipComponent, {
            cloneClassName: `${styles.tooltip} ${styles[tooltipModifier]}`,
            ref: tooltipRef,
          })}
        </>
      )}
      <div className={`${styles.body} ${bodyClassName}`}>{children}</div>
    </fieldset>
  );
};

export default Fieldset;
id=55ea3e415b31b834004bee9f5367fbfb420bbeef'>components</a>/<a href='/www.armandphilippot.com/tree/src/components/templates?id=55ea3e415b31b834004bee9f5367fbfb420bbeef'>templates</a>/<a href='/www.armandphilippot.com/tree/src/components/templates/page?id=55ea3e415b31b834004bee9f5367fbfb420bbeef'>page</a>/<a href='/www.armandphilippot.com/tree/src/components/templates/page/loading-page-comments.test.tsx?id=55ea3e415b31b834004bee9f5367fbfb420bbeef'>loading-page-comments.test.tsx</a></div><div class='content'>blob: b9ccb3e1b1c4e64c965cd621274e4b37786cd193 (<a href='/www.armandphilippot.com/plain/src/components/templates/page/loading-page-comments.test.tsx?id=55ea3e415b31b834004bee9f5367fbfb420bbeef'>plain</a>)
<table summary='blob content' class='blob'>
<tr><td class='linenumbers'><pre><a id='n1' href='#n1'>1</a>
<a id='n2' href='#n2'>2</a>
<a id='n3' href='#n3'>3</a>
<a id='n4' href='#n4'>4</a>
<a id='n5' href='#n5'>5</a>
<a id='n6' href='#n6'>6</a>
<a id='n7' href='#n7'>7</a>
<a id='n8' href='#n8'>8</a>
<a id='n9' href='#n9'>9</a>
<a id='n10' href='#n10'>10</a>
<a id='n11' href='#n11'>11</a>
<a id='n12' href='#n12'>12</a>
<a id='n13' href='#n13'>13</a>
</pre></td>
<td class='lines'><pre><code>