"use client"

import { useRef } from "react"

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

import { IconByIconName } from "@/components/Icons/IconByIconName"
import { trackAccordionClick } from "@/utils/tracking"

import Body from "../../Text/Body"
import Subtitle from "../../Text/Subtitle"
import { accordionItemVariants } from "./variants"

import styles from "./accordionItem.module.css"

import type { AccordionItemProps } from "./accordionItem"

export default function AccordionItem({
  children,
  icon,
  iconName,
  title,
  theme,
  variant,
  className,
  trackingId,
  subtitle,
}: AccordionItemProps) {
  const contentRef = useRef<HTMLDivElement>(null)
  const detailsRef = useRef<HTMLDetailsElement>(null)

  const IconComp = icon
    ? icon
    : iconName && (
        <IconByIconName
          iconName={iconName}
          color="Icon/Interactive/Default"
          size={24}
        />
      )

  function toggleAccordion() {
    const details = detailsRef.current
    const content = contentRef.current
    if (details && content) {
      if (details.open) {
        content.style.maxHeight = `${content.scrollHeight}px`
        content.addEventListener(
          "transitionend",
          () => {
            // Remove maxHeight after transition to allow content to transition multiple times
            content.style.maxHeight = "none"
          },
          { once: true }
        )
        if (trackingId) {
          trackAccordionClick(trackingId)
        }
      } else {
        content.style.maxHeight = "0"
      }
    }
  }

  return (
    <li className={accordionItemVariants({ className, variant, theme })}>
      <details ref={detailsRef} onToggle={toggleAccordion}>
        <summary className={styles.summary}>
          {IconComp}
          {variant === "sidepeek" ? (
            <Subtitle
              className={styles.title}
              type="two"
              color="baseTextHighContrast"
            >
              {title}
            </Subtitle>
          ) : (
            <div className={styles.title}>
              {subtitle ? (
                <Subtitle type="two" color="baseTextHighContrast">
                  {title}
                </Subtitle>
              ) : (
                <Body textTransform="bold" color="baseTextHighContrast">
                  {title}
                </Body>
              )}
              {subtitle && <Body color="baseTextHighContrast">{subtitle}</Body>}
            </div>
          )}
          <MaterialIcon
            icon="keyboard_arrow_down"
            className={styles.chevron}
            color="Icon/Interactive/Default"
            size={20}
          />
        </summary>
        <div ref={contentRef} className={styles.content}>
          {children}
        </div>
      </details>
    </li>
  )
}
