"use client";

import type { ReactNode } from "react";
import { useState, Fragment } from "react";
import classNames from "classnames/dedupe";
import type { DOMProps } from "../../types/dom";
import { Accordion } from "./Accordion";
import { Divider } from "../Divider";
import "./AccordionList.css";

export interface AccordionListProps extends DOMProps {
  /** Custom class name for setting specific CSS */
  className?: string;
  /** Array of accordion items with header and details content */
  content: Array<{
    /** Unique identifier for the accordion item (used as React key) */
    id: string;
    header: string | ReactNode;
    details: string | ReactNode;
  }>;
  /** Callback that fires when an accordion is opened */
  onOpen?: (id: string) => void;
  /** Callback that fires when an accordion is closed */
  onClose?: (id: string) => void;
  /** Allow multiple accordions to be open at the same time (default: false) */
  allowMultiple?: boolean;
}

const AccordionList = (props: AccordionListProps) => {
  const {
    className,
    content,
    onOpen,
    onClose,
    allowMultiple = false,
    ...rest
  } = props;
  const [openIds, setOpenIds] = useState<Set<string>>(new Set());

  const classes = classNames("mobius", "mobius-accordion-list", className);

  const handleAccordionChange = (id: string, isOpen: boolean) => {
    setOpenIds(prev => {
      const newSet = new Set(prev);
      if (isOpen) {
        if (!allowMultiple) {
          newSet.clear();
        }
        newSet.add(id);
      } else {
        newSet.delete(id);
      }
      return newSet;
    });

    if (isOpen) {
      onOpen?.(id);
    } else {
      onClose?.(id);
    }
  };

  return (
    <div className={classes} {...rest}>
      {content.map((item, index) => {
        const { id, header, details } = item;
        const isOpen = openIds.has(id);
        return (
          <Fragment key={id}>
            <Accordion
              startOpen={isOpen}
              showText={header}
              hideText={header}
              onChange={isOpen => handleAccordionChange(id, isOpen)}
            >
              {details}
            </Accordion>
            {index < content.length - 1 && <Divider />}
          </Fragment>
        );
      })}
    </div>
  );
};

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