"use client"

import { cx } from "class-variance-authority"
import NextLink from "next/link"
import { useEffect, useState } from "react"
import {
  Breadcrumbs as BreadcrumbsRAC,
  Button as ButtonRAC,
  Dialog as DialogRAC,
  DialogTrigger as DialogTriggerRAC,
  OverlayArrow as OverlayArrowRAC,
  Popover as PopoverRAC,
} from "react-aria-components"
import { useIntl } from "react-intl"

import { debounce } from "@scandic-hotels/common/utils/debounce"

import { Arrow } from "./Arrow"
import { Breadcrumb } from "./Breadcrumb"
import { splitBreadcrumbs } from "./utils"
import { variants } from "./variants"

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

import { MaterialIcon } from "../Icons/MaterialIcon"
import { Typography } from "../Typography"
import { BreadcrumbsProps } from "./types"

export function Breadcrumbs({
  breadcrumbs,
  color,
  size,
  isThemed,
}: BreadcrumbsProps) {
  const intl = useIntl()

  // using a ref instead to detect when the element is available and forcing a render
  const [element, attachRef] = useState<HTMLButtonElement | null>(null)
  const [isTooltipDisabled, setIsTooltipDisabled] = useState(false)

  useEffect(() => {
    const observer = new ResizeObserver(
      debounce(([entry]) => {
        const el = entry.target
        setIsTooltipDisabled(el.clientWidth >= el.scrollWidth)
      }, 200)
    )

    if (element) {
      observer.observe(element)
    }

    return () => {
      if (element) {
        observer.unobserve(element)
      }
    }
  }, [element])

  if (!breadcrumbs?.length) {
    return null
  }

  const classNames = variants({
    color,
    size,
    isThemed,
  })

  const [homeBreadcrumb, remainingBreadcrumbs, lastBreadcrumb] =
    splitBreadcrumbs(breadcrumbs)

  return (
    <nav
      aria-label={intl.formatMessage({
        id: "breadcrumbs.label",
        defaultMessage: "Breadcrumbs",
      })}
      className={classNames}
    >
      <BreadcrumbsRAC className={styles.breadcrumbs}>
        <Breadcrumb
          href={homeBreadcrumb.href}
          aria-label={homeBreadcrumb.title}
        >
          <MaterialIcon icon="home" size={20} color="CurrentColor" />
        </Breadcrumb>

        {/* These breadcrumbs are visible on mobile only */}
        {remainingBreadcrumbs.length >= 3 ? (
          <>
            <Breadcrumb
              href={remainingBreadcrumbs[0].href!}
              className={styles.mobile}
            >
              {remainingBreadcrumbs[0].title}
            </Breadcrumb>
            <Breadcrumb className={styles.mobile}>
              <DialogTriggerRAC>
                <Typography variant="Label/xsRegular">
                  {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */}
                  <ButtonRAC className={styles.showMoreButton}>…</ButtonRAC>
                </Typography>
                <PopoverRAC>
                  <DialogRAC className={styles.dialog}>
                    {remainingBreadcrumbs.slice(1).map((breadcrumb) => (
                      <Typography
                        key={breadcrumb.uid}
                        variant="Label/xsRegular"
                      >
                        <NextLink
                          href={breadcrumb.href!}
                          className={styles.dialogLink}
                        >
                          {breadcrumb.title}
                        </NextLink>
                      </Typography>
                    ))}
                  </DialogRAC>
                </PopoverRAC>
              </DialogTriggerRAC>
              <MaterialIcon
                icon="chevron_right"
                size={20}
                aria-hidden="true"
                color="CurrentColor"
              />
            </Breadcrumb>
          </>
        ) : (
          remainingBreadcrumbs.map((breadcrumb) => (
            <Breadcrumb
              key={breadcrumb.uid}
              href={breadcrumb.href}
              className={styles.mobile}
            >
              {breadcrumb.title}
            </Breadcrumb>
          ))
        )}

        {/* These breadcrumbs are visible on desktop only */}
        {remainingBreadcrumbs.map((breadcrumb) => (
          <Breadcrumb
            key={breadcrumb.uid}
            href={breadcrumb.href}
            className={styles.desktop}
          >
            {breadcrumb.title}
          </Breadcrumb>
        ))}

        {/* Current page breadcrumb */}
        <Breadcrumb>
          <DialogTriggerRAC>
            <Typography variant="Label/xsBold">
              <ButtonRAC
                className={cx(styles.showMoreButton, styles.lastBreadcrumb)}
                ref={attachRef}
                isDisabled={isTooltipDisabled}
              >
                {lastBreadcrumb.title}
              </ButtonRAC>
            </Typography>
            <PopoverRAC placement="bottom" offset={16}>
              <DialogRAC className={styles.tooltip}>
                <OverlayArrowRAC>
                  <Arrow color="black" size="small" />
                </OverlayArrowRAC>
                <Typography variant="Label/xsRegular">
                  <span>{lastBreadcrumb.title}</span>
                </Typography>
              </DialogRAC>
            </PopoverRAC>
          </DialogTriggerRAC>
        </Breadcrumb>
      </BreadcrumbsRAC>
    </nav>
  )
}
