"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 { twMerge } from "tailwind-merge";
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;
  position: number;
  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 function SystemNoticesHost({ className }: { className?: string }) {
  const pathname = usePathname() || "/dashboard";
  const [items, setItems] = useState<SystemNotice[]>([]);

  const visibleItems = useMemo(() => {
    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(() => {
    let active = true;
    async function load() {
      try {
        const res = await fetch(`/api/system-notices?path=${encodeURIComponent(pathname)}`, {
          method: "GET",
          headers: { "content-type": "application/json" },
        });
        if (!res.ok) {
          if (active) setItems([]);
          return;
        }
        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([]);
      }
    }
    load();
    return () => {
      active = false;
    };
  }, [pathname]);

  const hasVisibleItems = visibleItems.length > 0;

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

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

  if (!hasVisibleItems || typeof document === "undefined") return null;

  const firstNotice = visibleItems[0];
  const baseTheme = normalizeTheme(firstNotice?.theme ?? null, firstNotice?.variant ?? "info");
  const canDismissAny = visibleItems.some((n) => n.dismiss_mode !== "sticky");
  const WatermarkIcon = getIcon(baseTheme.watermark_icon);

  const overlay = createPortal(
    <>
      <div
        className={twMerge("no-print fixed inset-x-0 top-0 z-[500] w-full overflow-hidden border-b", className)}
        style={{
          borderColor: `${baseTheme.accent}33`,
          background: baseTheme.background,
          color: baseTheme.text,
        }}
      >
        {WatermarkIcon ? (
          <div className="pointer-events-none absolute -right-2 -top-5 opacity-[0.12]">
            <WatermarkIcon size={88} style={{ color: baseTheme.text, 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">
            <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}

          {canDismissAny ? (
            <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 border-black/10 bg-black/5 text-black/55 transition hover:bg-black/10"
              aria-label="Fechar"
              title="Fechar"
            >
              <X className="h-4 w-4" />
            </button>
          ) : null}
        </div>
      </div>
      <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>
    </>,
    document.body
  );

  return overlay;
}
