"use client";

import cx from "classnames";
import React, { ReactNode } from "react";

import { useHydrationSafeId } from "../../utils/hooks";

import AccordionHeader, { type AccordionHeaderProps } from "./AccordionHeader";

const CLASS_ROOT = "accordion__item";

export interface AccordionItemProps
  extends Pick<AccordionHeaderProps, "renderTitle"> {
  /** Accordion item id (automatically generated by default)  */
  id?: string;
  /** Open state indication */
  isActive?: boolean;
  /** Custom header renderer. Receives title, id and isActive props as function parameters. */
  renderHeader?: (title: string, id: string, isActive: boolean) => ReactNode;
  /** Title of accordion item */
  title: string;
  /** Additional CSS classes */
  className?: string;
  /** Accordion item content */
  children: ReactNode;
  /** Additional HTML attributes */
  [key: string]: any;
}

const AccordionItem: React.FC<AccordionItemProps> = ({
  id,
  isActive,
  title,
  renderTitle,
  renderHeader,
  children,
  className,
  ...other
}) => {
  const classes = cx(CLASS_ROOT, className);
  const currentId = useHydrationSafeId(id);

  return (
    <li className={classes}>
      {renderHeader ? (
        renderHeader(title, currentId, isActive || false)
      ) : (
        <AccordionHeader
          id={currentId}
          isActive={isActive}
          title={title}
          renderTitle={renderTitle}
          {...other}
        />
      )}
      <div
        id={`${currentId}-section`}
        role="region"
        aria-labelledby={currentId}
        className={cx("accordion__body", { "is-active": isActive })}
        {...(isActive ? {} : { hidden: true })}
      >
        {children}
      </div>
    </li>
  );
};

AccordionItem.displayName = "AccordionItem";

export { AccordionItem };
