import { type PropsWithChildren, useState } from "react"

import Caption from "@/components/TempDesignSystem/Text/Caption"

import { tooltipVariants } from "./variants"

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

import type { TooltipPosition, TooltipProps } from "@/types/components/tooltip"

export function Tooltip<P extends TooltipPosition>({
  heading,
  text,
  position,
  arrow,
  children,
  isTouchable = false,
}: PropsWithChildren<TooltipProps<P>>) {
  const className = tooltipVariants({ position, arrow })
  const [isActive, setIsActive] = useState(false)

  function handleToggle() {
    setIsActive((prevState) => !prevState)
  }

  function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault()
      handleToggle()
    }
  }

  return (
    <div
      className={styles.tooltipContainer}
      role="tooltip"
      aria-label={text}
      tabIndex={0}
      onClick={isTouchable ? undefined : handleToggle}
      onTouchStart={isTouchable ? handleToggle : undefined}
      onKeyDown={handleKeyDown}
      data-active={isActive}
    >
      <div className={className}>
        {heading && (
          <Caption type="bold" color="white">
            {heading}
          </Caption>
        )}
        {text && <Caption color="white">{text}</Caption>}
      </div>
      {children}
    </div>
  )
}
