import React, { forwardRef } from "react";
import { Icons } from "../icons";

import {
  StyledRoot,
  StyledItem,
  StyledHeader,
  StyledTrigger,
  StyledContent,
  IconPlus,
  IconMinus,
  Indicator,
} from "./accordion.styled";

export type AccordionItemType = React.ComponentProps<typeof StyledItem> & {
  header: React.ReactElement;
  body: React.ReactElement;
};
export type AccordionItemsProps = AccordionItemType[];

interface BaseProps {
  /**
   * The accordion items
   */
  items: AccordionItemsProps;
  /**
   * [Radix Documentation](https://www.radix-ui.com/primitives/docs/components/accordion#header)
   */
  headerProps?: React.ComponentProps<typeof StyledHeader>;
  /**
   * [Radix Documentation](https://www.radix-ui.com/primitives/docs/components/accordion#trigger)
   */
  triggerProps?: React.ComponentProps<typeof StyledTrigger>;
  /**
   * [Radix Documentation](https://www.radix-ui.com/primitives/docs/components/accordion#content)
   */
  contentProps?: React.ComponentProps<typeof StyledContent>;
}

/**
 * Based on [Radix Primitives Accordion](https://www.radix-ui.com/primitives/docs/components/accordion).
 *
 * Accordion is a component that consists of vertically stacked set of interactive headings that each reveal an associated section of content.
 */
export const Accordion = forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof StyledRoot> & BaseProps
>((props, ref) => {
  const { items, headerProps, triggerProps, contentProps, ...rootProps } = props;

  return (
    <StyledRoot {...rootProps} ref={ref}>
      {items.map(({ value, header, body, ...perItemProps }) => (
        <StyledItem key={value} value={value} {...perItemProps}>
          <StyledHeader {...headerProps}>
            <StyledTrigger {...triggerProps}>
              {header}
              <Indicator>
                <IconPlus aria-hidden>
                  <Icons.Minus />
                </IconPlus>
                <IconMinus aria-hidden>
                  <Icons.Minus />
                </IconMinus>
              </Indicator>
            </StyledTrigger>
          </StyledHeader>
          <StyledContent {...contentProps}>{body}</StyledContent>
        </StyledItem>
      ))}
    </StyledRoot>
  );
});
Accordion.displayName = "Accordion";

export const AccordionRootSelector = StyledRoot.toString();
export const AccordionItemSelector = StyledItem.toString();
export const AccordionHeaderSelector = StyledHeader.toString();
export const AccordionTriggerSelector = StyledTrigger.toString();
export const AccordionContentSelector = StyledContent.toString();
export const AccordionIndicatorSelector = Indicator.toString();
export const AccordionIconPlusSelector = IconPlus.toString();
export const AccordionIconMinusSelector = IconMinus.toString();
