import clsx from 'clsx';
import React from 'react';
import { useExpand } from '../../../hooks/useExpand/useExpand';
import { Button, ButtonContext } from '../../Buttons';
import { FormGrid } from '../../FormStation/FormGrid/FormGrid';
import { IconName } from '../../Icons';
import classes from './FormGroup.scss';

export interface FormGroupProps {
  className?: string;
  /** Group title to display */
  title: string;
  /** Whether the group is collapsible (default: false) */
  isCollapsible?: boolean;
  /** Whether the collapsible group is expanded by default (default: true) */
  defaultExpanded?: boolean;
}

export const FormGroup: React.FC<FormGroupProps> = ({
  className = '',
  title,
  children,
  isCollapsible = false,
  defaultExpanded = true,
}) => {
  const { isExpanded, toggleExpanded } = useExpand(defaultExpanded);
  return (
    <div className={clsx(classes.container, 'FormGroup-container', className)}>
      <div
        className={clsx(classes.title, {
          [classes.collapsible]: isCollapsible,
          [classes.collapsed]: isCollapsible && !isExpanded,
        })}
        onClick={() => {
          isCollapsible && toggleExpanded();
        }}
      >
        {isCollapsible && (
          <Button
            icon={IconName.ChevronRight}
            className={clsx(classes.button, {
              [classes.rotated]: isExpanded,
            })}
            buttonContext={ButtonContext.None}
          />
        )}
        <div>{title}</div>
      </div>
      <div
        className={clsx(classes.content, {
          [classes.expanded]: !isCollapsible || isExpanded,
        })}
        aria-hidden={isCollapsible && !isExpanded}
        {...(isCollapsible && !isExpanded ? { inert: '' } : {})}
      >
        <FormGrid edgeToEdgeContent={true}>{children}</FormGrid>
      </div>
    </div>
  );
};
