"use client";

import { AlertTriangle, Bell, Info, Lock, X } from "lucide-react";
import { useEffect, useState } from "react";
import { getActiveNotifications } from "@/services/saas-admin-service";
import { SystemNotification } from "@/types/saas-admin";

export function TenantBroadcastBanner() {
  const [notifications, setNotifications] = useState<SystemNotification[]>([]);
  const [dismissedIds, setDismissedIds] = useState<string[]>(() => {
    if (typeof window !== "undefined") {
      try {
        const saved = localStorage.getItem("dismissed_notifications");
        return saved ? JSON.parse(saved) : [];
      } catch {
        return [];
      }
    }
    return [];
  });

  const handleDismiss = (id: string) => {
    setDismissedIds((prev) => {
      const updated = Array.from(new Set([...prev, id]));
      if (typeof window !== "undefined") {
        try {
          localStorage.setItem("dismissed_notifications", JSON.stringify(updated));
        } catch {}
      }
      return updated;
    });
  };

  useEffect(() => {
    async function loadNotifications() {
      try {
        const notifs = await getActiveNotifications();
        setNotifications(notifs);
      } catch {
        // quiet error
      }
    }
    loadNotifications();

    const handleNewNotif = (e: any) => {
      if (e.detail) {
        setNotifications((prev) => [e.detail, ...prev.filter((n) => n.id !== e.detail.id)]);
      } else {
        loadNotifications();
      }
    };

    const handleStorageEvent = (e: StorageEvent) => {
      if (e.key === "latest_system_notification" && e.newValue) {
        try {
          const parsed = JSON.parse(e.newValue);
          if (parsed) {
            setNotifications((prev) => [parsed, ...prev.filter((n) => n.id !== parsed.id)]);
          }
        } catch {}
      }
    };

    window.addEventListener("system-notification-created", handleNewNotif);
    window.addEventListener("storage", handleStorageEvent);
    return () => {
      window.removeEventListener("system-notification-created", handleNewNotif);
      window.removeEventListener("storage", handleStorageEvent);
    };
  }, []);

  const activeNotifs = notifications.filter((n) => !dismissedIds.includes(n.id));

  if (activeNotifs.length === 0) return null;

  return (
    <div className="w-full space-y-2 px-4 pt-4">
      {activeNotifs.map((notif) => {
        const isWarning = notif.type === "WARNING";
        const isBlock = notif.type === "BLOCK";

        return (
          <div
            key={notif.id}
            className={`flex items-start justify-between rounded-xl p-4 shadow-sm text-xs font-medium transition-all ${
              isBlock
                ? "bg-rose-500/15 border border-rose-500/30 text-rose-700 dark:text-rose-300"
                : isWarning
                ? "bg-amber-500/15 border border-amber-500/30 text-amber-800 dark:text-amber-300"
                : "bg-blue-500/15 border border-blue-500/30 text-blue-800 dark:text-blue-300"
            }`}
          >
            <div className="flex items-start gap-3">
              <div className="mt-0.5">
                {isBlock ? (
                  <Lock className="h-5 w-5 text-rose-600" />
                ) : isWarning ? (
                  <AlertTriangle className="h-5 w-5 text-amber-600" />
                ) : (
                  <Bell className="h-5 w-5 text-blue-600" />
                )}
              </div>
              <div>
                <p className="font-bold text-sm">{notif.title}</p>
                <p className="mt-0.5 leading-relaxed">{notif.message}</p>
              </div>
            </div>

            <button
              onClick={() => handleDismiss(notif.id)}
              className="p-1 opacity-70 hover:opacity-100 transition-opacity"
              title="Fechar aviso"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
        );
      })}
    </div>
  );
}
