"use client"

import { cx } from "class-variance-authority"
import Link from "next/link"
import { useEffect, useState } from "react"
import {
  Breadcrumbs as AriaBreadcrumbs,
  Button,
  Dialog,
  DialogTrigger,
  OverlayArrow,
  Popover,
} from "react-aria-components"
import { useIntl } from "react-intl"

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

import { debounce } from "@/utils/debounce"

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

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

import type { BreadcrumbsProps } from "./breadcrumbs"

export default function Breadcrumbs({
  breadcrumbs,
  color,
  size,
}: 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 = breadcrumbsVariants({
    color,
    size,
  })

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

  return (
    <nav
      aria-label={intl.formatMessage({
        defaultMessage: "Breadcrumbs",
      })}
      className={classNames}
    >
      <AriaBreadcrumbs className={styles.list}>
        <Breadcrumb
          href={homeBreadcrumb.href}
          aria-label={homeBreadcrumb.title}
        >
          <MaterialIcon
            icon="home"
            size={20}
            color="Icon/Interactive/Secondary"
          />
        </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}>
              <DialogTrigger>
                <Typography variant="Label/xsRegular">
                  {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */}
                  <Button className={styles.button}>…</Button>
                </Typography>
                <Popover>
                  <Dialog className={styles.dialog}>
                    {remainingBreadcrumbs.slice(1).map((breadcrumb) => (
                      <Typography
                        key={breadcrumb.uid}
                        variant="Label/xsRegular"
                      >
                        <Link
                          href={breadcrumb.href!}
                          className={styles.dialogLink}
                        >
                          {breadcrumb.title}
                        </Link>
                      </Typography>
                    ))}
                  </Dialog>
                </Popover>
              </DialogTrigger>
              <MaterialIcon
                icon="chevron_right"
                size={20}
                aria-hidden="true"
                color="Icon/Interactive/Secondary"
              />
            </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>
          <DialogTrigger>
            <Typography variant="Label/xsBold">
              <Button
                className={cx(styles.button, styles.tooltipTrigger)}
                ref={attachRef}
                isDisabled={isTooltipDisabled}
              >
                {lastBreadcrumb.title}
              </Button>
            </Typography>
            <Popover placement="bottom" offset={16}>
              <Dialog className={styles.tooltip}>
                <OverlayArrow>
                  <Arrow color="black" size="small" />
                </OverlayArrow>
                <Typography variant="Label/xsRegular">
                  <span>{lastBreadcrumb.title}</span>
                </Typography>
              </Dialog>
            </Popover>
          </DialogTrigger>
        </Breadcrumb>
      </AriaBreadcrumbs>
    </nav>
  )
}
