import { useEffect, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import { translateReactNode, usePlatformLanguage } from "../i18n/LanguageContext";

type AlertTone = "success" | "info" | "warning" | "danger";

type DismissibleAlertProps = {
  tone?: AlertTone;
  children: ReactNode;
  dismissible?: boolean;
  className?: string;
  compact?: boolean;
  floating?: boolean;
  resetKey?: string | number;
  dismissStorageKey?: string;
};

let floatingAlertRoot: HTMLElement | null = null;

function getFloatingAlertRoot(ariaLabel: string): HTMLElement | null {
  if (typeof document === "undefined") return null;
  if (floatingAlertRoot?.isConnected) {
    floatingAlertRoot.setAttribute("aria-label", ariaLabel);
    return floatingAlertRoot;
  }

  const existing = document.getElementById("app-floating-alerts");
  if (existing) {
    floatingAlertRoot = existing;
    floatingAlertRoot.setAttribute("aria-label", ariaLabel);
    return floatingAlertRoot;
  }

  floatingAlertRoot = document.createElement("div");
  floatingAlertRoot.id = "app-floating-alerts";
  floatingAlertRoot.className = "alert-floating-stack";
  floatingAlertRoot.setAttribute("aria-label", ariaLabel);
  document.body.appendChild(floatingAlertRoot);
  return floatingAlertRoot;
}

function resolveDismissStorageKey(dismissStorageKey: string | undefined, resetKey: string | number | undefined): string | null {
  if (!dismissStorageKey) return null;
  return `govoplan.alert.dismissed:${dismissStorageKey}:${resetKey ?? "default"}`;
}

function readDismissed(storageKey: string | null): boolean {
  if (!storageKey || typeof window === "undefined") return false;
  try {
    return window.localStorage.getItem(storageKey) === "1";
  } catch {
    return false;
  }
}

function writeDismissed(storageKey: string | null): void {
  if (!storageKey || typeof window === "undefined") return;
  try {
    window.localStorage.setItem(storageKey, "1");
  } catch {
    // localStorage may be unavailable in private or restricted contexts.
  }
}

export default function DismissibleAlert({
  tone = "info",
  children,
  dismissible = true,
  className = "",
  compact = false,
  floating = false,
  resetKey,
  dismissStorageKey
}: DismissibleAlertProps) {
  const { translateText } = usePlatformLanguage();
  const storageKey = resolveDismissStorageKey(dismissStorageKey, resetKey);
  const [alertState, setAlertState] = useState(() => ({ storageKey, visible: !readDismissed(storageKey) }));
  const visible = alertState.storageKey === storageKey ? alertState.visible : !readDismissed(storageKey);

  useEffect(() => {
    setAlertState({ storageKey, visible: !readDismissed(storageKey) });
  }, [storageKey, resetKey, children]);

  if (!visible) return null;
  const renderedChildren = translateReactNode(children, translateText);
  const floatingLabel = translateText("i18n:govoplan-core.application_notices");

  function dismiss() {
    writeDismissed(storageKey);
    setAlertState({ storageKey, visible: false });
  }

  const role = tone === "danger" || tone === "warning" ? "alert" : "status";
  const alert = (
    <div
      className={`alert ${tone}${compact ? " compact-alert" : ""}${floating ? " alert-floating" : ""} alert-dismissible ${className}`.trim()}
      role={role}
      aria-live={role === "alert" ? "assertive" : "polite"}
    >
      <div className="alert-message">{renderedChildren}</div>
      {dismissible && (
        <button type="button" className="alert-dismiss" aria-label={translateText("i18n:govoplan-core.dismiss_notice.ce08c9ad")} onClick={dismiss}>
          <X size={16} strokeWidth={2.4} aria-hidden="true" />
        </button>
      )}
    </div>
  );

  if (!floating) return alert;
  const root = getFloatingAlertRoot(floatingLabel);
  return root ? createPortal(alert, root) : alert;
}
