import type { KeyboardEvent, ReactNode } from "react";
import type { DOMProps } from "../../types";
import classNames from "classnames/dedupe";
import { Flex } from "../Flex";
import { Icon } from "../Icon";
import { chevronDown } from "@simplybusiness/icons";

export type AccordionLinkElementType =
  | "h1"
  | "h2"
  | "h3"
  | "h4"
  | "h5"
  | "h6"
  | "span";
export type AccordionElementType = HTMLDivElement;

export interface AccordionLinkProps extends DOMProps {
  text: string | ReactNode;
  elementType?: AccordionLinkElementType;
  onClick?: (e?: React.MouseEvent) => void;
  toggle: () => void;
  headerChildren?: ReactNode;
  ariaExpanded: boolean | undefined;
  accordionId: string;
  contentId: string;
}

export const AccordionLink = ({
  text,
  elementType: LinkElement = "span",
  toggle,
  onClick,
  headerChildren,
  ariaExpanded,
  accordionId,
  contentId,
}: AccordionLinkProps) => {
  const linkClasses = classNames("mobius-accordion__link", {
    "--is-open": ariaExpanded,
  });
  const iconClasses = classNames("mobius-accordion__link-icon", {
    "--is-open": ariaExpanded,
  });
  const handleOnClick = (e?: React.MouseEvent): void => {
    if (onClick) {
      onClick(e);
    }
    toggle();
  };

  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === " " || e.key === "Enter") {
      toggle();
    }
  };

  if (headerChildren) {
    return (
      <Flex
        justifyContent="space-between"
        alignItems="center"
        className="mobius-accordion__header"
      >
        <div
          id={accordionId}
          className={linkClasses}
          onClick={handleOnClick}
          onKeyDown={handleKeyDown}
          role="button"
          tabIndex={0}
          aria-expanded={!!ariaExpanded}
          aria-controls={contentId}
        >
          <LinkElement className="mobius-accordion__link-text">
            {text}
          </LinkElement>
          <Icon icon={chevronDown} className={iconClasses} />
        </div>
        {headerChildren}
      </Flex>
    );
  }

  return (
    <div
      id={accordionId}
      className={linkClasses}
      onClick={handleOnClick}
      onKeyDown={handleKeyDown}
      role="button"
      tabIndex={0}
      aria-expanded={!!ariaExpanded}
      aria-controls={contentId}
    >
      <LinkElement className="mobius-accordion__link-text">{text}</LinkElement>
      <Icon icon={chevronDown} className={iconClasses} />
    </div>
  );
};
