"use client";

import cx from "classnames";
import React from "react";

import { Icon } from "../Icon";

import HeadingContext from "./HeadingContext";

const CLASS_ROOT = "accordion";

export interface AccordionHeaderProps {
  /** Header id */
  id: string;
  /** Active state */
  isActive?: boolean;
  /** Header title */
  title: string;
  renderTitle?: (title: string) => React.ReactNode;
  /** Additional CSS classes */
  className?: string;
  /** Custom toggle attribute for specialized accordions (defaults to 'data-accordion-toggle') */
  toggleAttribute?: string;

  /** Additional HTML attributes */
  [key: string]: any;
}

const AccordionHeader: React.FC<AccordionHeaderProps> = ({
  className,
  title,
  renderTitle,
  id,
  isActive,
  toggleAttribute = "data-accordion-toggle",
  ...other
}) => {
  const headingLevel = React.useContext(HeadingContext);
  const Heading = `h${headingLevel || 3}` as
    | "h1"
    | "h2"
    | "h3"
    | "h4"
    | "h5"
    | "h6";

  const buttonProps = {
    type: "button" as const,
    "aria-expanded": isActive,
    className: `${CLASS_ROOT}__button`,
    "aria-controls": `${id}-section`,
    id,
    [toggleAttribute]: true,
    ...other,
  };

  return (
    <Heading className={cx(`${CLASS_ROOT}__header`, className)}>
      <button {...buttonProps}>
        {renderTitle ? (
          renderTitle(title)
        ) : (
          <span className="accordion__title">{title}</span>
        )}
        <Icon
          className={`${CLASS_ROOT}__icon`}
          name="chevron-down"
          size="medium"
        />
      </button>
    </Heading>
  );
};

AccordionHeader.displayName = "AccordionHeader";

export default AccordionHeader;
