import { useId, useState, type ReactNode } from "react";
import { cx } from "./utils";
import { Icon } from "./Icon";

export type AccordionProps = {
  label: ReactNode;
  defaultOpen?: boolean;
  children: ReactNode;
  className?: string;
};

export function Accordion({ label, defaultOpen = false, children, className }: AccordionProps) {
  const [open, setOpen] = useState(defaultOpen);
  const id = useId();
  return (
    <div className={cx("mmg-accordion", className)} data-open={open}>
      <button
        type="button"
        className="mmg-accordion__btn"
        aria-expanded={open}
        aria-controls={id}
        onClick={() => setOpen((v) => !v)}
      >
        <span>{label}</span>
        <Icon name="arrow-down-line" className="mmg-accordion__chevron" />
      </button>
      <div id={id} role="region" className="mmg-accordion__panel">
        {children}
      </div>
    </div>
  );
}
