"use client";

import { useEffect, useMemo, useState } from "react";
import { usePathname } from "next/navigation";
import {
  ArrowRight,
  BadgePercent,
  Bell,
  CalendarClock,
  Info,
  Megaphone,
  ShieldCheck,
  Sparkles,
  TriangleAlert,
  X,
  type LucideIcon,
} from "lucide-react";
import { createPortal } from "react-dom";

type ThemeConfig = {
  background?: string;
  text?: string;
  accent?: string;
  inline_icon?: string;
  watermark_icon?: string;
  cta_label?: string;
  cta_url?: string;
  cta_new_tab?: boolean;
};

type SystemNotice = {
  id: string;
  scope: string;
  title: string | null;
  message: string;
  variant: string;
  dismiss_mode: string;
  active: boolean;
  position: number;
  start_at: string | null;
  end_at: string | null;
  show_on_paths: string[] | null;
  hide_on_paths: string[] | null;
  theme: ThemeConfig | Record<string, unknown> | null;
  updated_at: string | null;
};

const ICONS: Record<string, LucideIcon> = {
  megaphone: Megaphone,
  bell: Bell,
  sparkles: Sparkles,
  "shield-check": ShieldCheck,
  "badge-percent": BadgePercent,
  "calendar-clock": CalendarClock,
  "triangle-alert": TriangleAlert,
  info: Info,
};

function variantFallback(variant: string) {
  if (variant === "success") return { background: "#ECFDF5", text: "#065F46", accent: "#10B981" };
  if (variant === "warning") return { background: "#FFFBEB", text: "#92400E", accent: "#F59E0B" };
  if (variant === "danger") return { background: "#FFF1F2", text: "#9F1239", accent: "#F43F5E" };
  return { background: "#EFF6FF", text: "#1D4ED8", accent: "#3B82F6" };
}

function normalizeTheme(theme: SystemNotice["theme"], variant: string) {
  const base = variantFallback(String(variant || "info"));
  const src = theme && typeof theme === "object" && !Array.isArray(theme) ? (theme as ThemeConfig) : {};
  return {
    background: src.background || base.background,
    text: src.text || base.text,
    accent: src.accent || base.accent,
    inline_icon: src.inline_icon || "",
    watermark_icon: src.watermark_icon || "",
    cta_label: src.cta_label || "",
    cta_url: src.cta_url || "",
    cta_new_tab: Boolean(src.cta_new_tab),
  };
}

function getIcon(name: string | null | undefined) {
  return ICONS[String(name || "").trim()] || null;
}

function getDismissKey(notice: SystemNotice) {
  const version = String(notice.updated_at || "");
  return `ktl_system_notice_dismissed__${notice.id}__${version}`;
}

export default function SystemNoticesHost() {
  const pathname = usePathname() || "/";
  const [items, setItems] = useState<SystemNotice[]>([]);
  const [mounted, setMounted] = useState(false);
  const [loading, setLoading] = useState(true);

  const scope = "owner";

  const visibleItems = useMemo(() => {
    if (!mounted) return [];
    return items.filter((notice) => {
      if (notice.dismiss_mode === "sticky") return true;
      const key = getDismissKey(notice);
      try {
        if (notice.dismiss_mode === "session") return window.sessionStorage.getItem(key) !== "1";
        return window.localStorage.getItem(key) !== "1";
      } catch {
        return true;
      }
    });
  }, [items]);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted) return;
    let active = true;
    async function load() {
      setLoading(true);
      try {
        const res = await fetch(
          `/api/system-notices?mode=display&scope=${encodeURIComponent(scope)}&path=${encodeURIComponent(pathname)}`,
          {
            method: "GET",
            headers: { "content-type": "application/json" },
          }
        );
        const json = (await res.json().catch(() => null)) as { notices?: SystemNotice[] } | null;
        const list = Array.isArray(json?.notices) ? json!.notices! : [];
        if (active) setItems(list);
      } catch {
        if (active) setItems([]);
      } finally {
        if (active) setLoading(false);
      }
    }
    load();
    return () => {
      active = false;
    };
  }, [mounted, pathname]);

  const hasVisibleItems = visibleItems.length > 0;
  const shouldRenderOverlay = loading || hasVisibleItems;
  const baseTheme = hasVisibleItems ? normalizeTheme(visibleItems[0]?.theme ?? null, visibleItems[0]?.variant ?? "info") : null;
  const WatermarkIcon = getIcon(baseTheme?.watermark_icon);

  useEffect(() => {
    if (!mounted) return;
    try {
      document.documentElement.style.setProperty("--ktl-system-notices-offset", shouldRenderOverlay ? "44px" : "0px");
    } catch {
      return;
    }
  }, [mounted, shouldRenderOverlay]);

  useEffect(() => {
    return () => {
      try {
        document.documentElement.style.setProperty("--ktl-system-notices-offset", "0px");
      } catch {
        return;
      }
    };
  }, []);

  const overlay =
    !mounted || !shouldRenderOverlay || typeof document === "undefined"
      ? null
      : createPortal(
          <div
            className="fixed inset-x-0 top-0 z-[500] w-full overflow-hidden border-b"
            style={
              baseTheme
                ? { borderColor: `${baseTheme.accent}33`, background: baseTheme.background, color: baseTheme.text }
                : { borderColor: "rgba(0,0,0,0.08)", background: "rgba(15,23,42,0.92)", color: "white" }
            }
          >
            {WatermarkIcon ? (
              <div className="pointer-events-none absolute -right-2 -top-5 opacity-[0.12]">
                <WatermarkIcon size={88} style={{ color: baseTheme?.text || "white", transform: "rotate(32deg)" }} />
              </div>
            ) : null}

            <div className="relative flex h-11 w-full items-center gap-3 px-4 sm:px-6">
              <div className="ticker-mask min-w-0 flex-1">
                {loading ? (
                  <div className="h-4 w-full animate-pulse rounded-full bg-black/10" />
                ) : (
                  <div className="ticker-track">
                    {[0, 1].map((dup) => (
                      <div key={dup} className="ticker-content">
                        {visibleItems.map((notice) => {
                          const theme = normalizeTheme(notice.theme, notice.variant);
                          const InlineIcon = getIcon(theme.inline_icon);
                          const text = `${notice.title ? `${notice.title}: ` : ""}${notice.message}`.trim();
                          return (
                            <div key={`${dup}-${notice.id}`} className="ticker-item" style={{ color: theme.text || baseTheme?.text }}>
                              {InlineIcon ? <InlineIcon className="h-3.5 w-3.5 shrink-0" style={{ color: theme.accent }} /> : null}
                              <span className="ticker-text">{text}</span>
                            </div>
                          );
                        })}
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {baseTheme?.cta_label && baseTheme?.cta_url ? (
                <a
                  href={baseTheme.cta_url}
                  target={baseTheme.cta_new_tab ? "_blank" : undefined}
                  rel={baseTheme.cta_new_tab ? "noreferrer noopener" : undefined}
                  className="inline-flex h-7 shrink-0 items-center gap-1 rounded-full border px-3 text-[11px] font-semibold transition hover:opacity-90"
                  style={{
                    borderColor: `${baseTheme.accent}40`,
                    background: `${baseTheme.accent}16`,
                    color: baseTheme.text,
                  }}
                >
                  <span>{baseTheme.cta_label}</span>
                  <ArrowRight className="h-3.5 w-3.5" />
                </a>
              ) : null}

              {visibleItems.some((n) => n.dismiss_mode !== "sticky") ? (
                <button
                  type="button"
                  onClick={() => {
                    setItems((prev) => {
                      const keep: typeof prev = [];
                      prev.forEach((notice) => {
                        if (notice.dismiss_mode === "sticky") {
                          keep.push(notice);
                          return;
                        }
                        const key = getDismissKey(notice);
                        try {
                          if (notice.dismiss_mode === "session") window.sessionStorage.setItem(key, "1");
                          else window.localStorage.setItem(key, "1");
                        } catch {
                          keep.push(notice);
                        }
                      });
                      return keep;
                    });
                  }}
                  className="inline-flex h-8 w-8 items-center justify-center rounded-full border transition"
                  style={
                    baseTheme
                      ? { borderColor: `${baseTheme.accent}22`, background: `${baseTheme.accent}14`, color: baseTheme.text }
                      : { borderColor: "rgba(0,0,0,0.12)", background: "rgba(0,0,0,0.06)", color: "rgba(255,255,255,0.75)" }
                  }
                  aria-label="Fechar"
                  title="Fechar"
                >
                  <X className="h-4 w-4" />
                </button>
              ) : null}
            </div>
          </div>,
          document.body
        );

  if (!mounted || !shouldRenderOverlay) return null;

  return (
    <>
      {overlay}
      <style jsx>{`
        .ticker-mask {
          overflow: hidden;
        }

        .ticker-track {
          display: flex;
          width: max-content;
          animation: ktl-ticker-move 22s linear infinite;
        }

        .ticker-mask:hover .ticker-track {
          animation-play-state: paused;
        }

        .ticker-content {
          display: inline-flex;
          align-items: center;
          gap: 28px;
          padding-right: 28px;
        }

        .ticker-item {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          white-space: nowrap;
          font-size: 13px;
          font-weight: 600;
          letter-spacing: -0.01em;
        }

        .ticker-text {
          opacity: 0.9;
        }

        @keyframes ktl-ticker-move {
          from {
            transform: translateX(0);
          }
          to {
            transform: translateX(-50%);
          }
        }
      `}</style>
    </>
  );
}
