import { useState } from "react";
import { createPortal } from "react-dom";

const TOOLTIP_HALF_WIDTH_PX = 144;
const TOOLTIP_VIEWPORT_PADDING_PX = 16;

export type ObserveRegionStatus =
  | "ready"
  | "missing-datasource"
  | "missing-loki-datasource"
  | "query-error";

function statusDotClass(status: ObserveRegionStatus): string {
  if (status === "ready") return "bg-success/60";
  if (status === "query-error") return "bg-danger";
  return "bg-warning";
}

function statusLabel(status: ObserveRegionStatus): string {
  if (status === "ready") return "Ready";
  if (status === "query-error") return "Query error";
  return "Missing datasource";
}

export function RegionStatusDot({
  status,
  errorMessage,
  fallbackErrorMessage,
}: {
  status: ObserveRegionStatus;
  errorMessage?: string;
  fallbackErrorMessage?: string;
}) {
  const [hovered, setHovered] = useState(false);
  const [tooltipPlacement, setTooltipPlacement] = useState<"above" | "below">("below");
  const [tooltipPosition, setTooltipPosition] = useState({ left: 0, top: 0 });
  const label = statusLabel(status);
  const detail =
    status === "query-error" ? errorMessage || fallbackErrorMessage || "Query failed" : "";

  return (
    <span className="relative inline-flex">
      <span
        role="img"
        aria-label={label}
        onMouseEnter={(event) => {
          const { left, right, top, bottom } = event.currentTarget.getBoundingClientRect();
          const placement =
            window.innerHeight - bottom >= 160 || window.innerHeight - bottom >= top
              ? "below"
              : "above";
          const minLeft = Math.min(
            TOOLTIP_HALF_WIDTH_PX + TOOLTIP_VIEWPORT_PADDING_PX,
            window.innerWidth / 2
          );
          const maxLeft = Math.max(
            minLeft,
            window.innerWidth - TOOLTIP_HALF_WIDTH_PX - TOOLTIP_VIEWPORT_PADDING_PX
          );

          setTooltipPlacement(placement);
          setTooltipPosition({
            left: Math.min(Math.max((left + right) / 2, minLeft), maxLeft),
            top: placement === "above" ? top - 8 : bottom + 8,
          });
          setHovered(true);
        }}
        onMouseLeave={() => setHovered(false)}
        className={`h-2 w-2 rounded-full ${statusDotClass(status)}`}
      />
      {hovered ? (
        createPortal(
          <span
            role="tooltip"
            style={tooltipPosition}
            className={`pointer-events-none fixed z-50 w-[18rem] max-w-[calc(100vw-2rem)] max-h-72 overflow-y-auto -translate-x-1/2 rounded-md border border-surface-2 bg-surface-1 px-2 py-1 text-[11px] font-medium text-text-primary shadow-lg ${tooltipPlacement === "above" ? "-translate-y-full" : ""}`}
          >
            <span className="grid gap-1">
              <span className="whitespace-nowrap">{label}</span>
              {detail ? (
                <span className="block max-w-full whitespace-normal break-words font-normal text-danger">
                  {detail}
                </span>
              ) : null}
            </span>
          </span>
          ,
          document.body
        )
      ) : null}
    </span>
  );
}
