"use client";

import { useState, useEffect } from "react";
import { AlertTriangle, AlertOctagon, Info } from "lucide-react";

interface SystemMessage {
  id: string;
  type: "info" | "warning" | "error" | "maintenance";
  title: string | null;
  message: string;
}

// Check if we're in development mode
const isDevelopment = process.env.NODE_ENV === "development";

/**
 * SystemMessagePopup
 *
 * Note: This component runs in root layout WITHOUT SessionProvider for performance.
 * Session-based dismissal tracking is done via API call which handles auth server-side.
 * This avoids requiring AuthProvider on all public pages.
 *
 * In development mode, alerts are logged to console instead of blocking the UI.
 */
export default function SystemMessagePopup() {
  const [activeMessages, setActiveMessages] = useState<SystemMessage[]>([]);

  useEffect(() => {
    const fetchMessages = async () => {
      try {
        const response = await fetch("/api/system-messages/active", {
          cache: "no-store",
        });
        if (response.ok) {
          const messages: SystemMessage[] = await response.json();

          // Filter out dismissed messages for this session (so new visits still see them)
          const dismissed = JSON.parse(
            sessionStorage.getItem("dismissed_messages_session") || "[]",
          );
          const visible = messages.filter((m) => !dismissed.includes(m.id));

          // In development, log to console instead of showing modal
          if (isDevelopment && visible.length > 0) {
            console.group("[DEV] System Messages (suppressed from UI)");
            visible.forEach((msg) => {
              const logMethod =
                msg.type === "error"
                  ? console.error
                  : msg.type === "warning"
                    ? console.warn
                    : console.info;
              logMethod(
                `[${msg.type.toUpperCase()}] ${msg.title || "System Alert"}: ${msg.message}`,
              );
            });
            console.groupEnd();
            return; // Don't show modal in development
          }

          setActiveMessages(visible);
        }
      } catch {
        console.error("Failed to load system messages");
      }
    };

    fetchMessages();
  }, []);

  const handleDismiss = async (id: string) => {
    // Remove from UI
    setActiveMessages((prev) => prev.filter((m) => m.id !== id));

    // Save to sessionStorage so next visit shows again
    const dismissed = JSON.parse(
      sessionStorage.getItem("dismissed_messages_session") || "[]",
    );
    sessionStorage.setItem(
      "dismissed_messages_session",
      JSON.stringify([...dismissed, id]),
    );

    // Track dismissal on server (API handles auth check server-side)
    try {
      await fetch("/api/system-messages/active", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messageId: id }),
      });
    } catch {
      // Silently ignore - dismissal tracking is non-critical
    }
  };

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

  return (
    <div className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-in fade-in duration-200">
      <div className="w-full max-w-md space-y-4 max-h-[85vh] overflow-y-auto">
        {activeMessages.map((msg) => {
          const isError = msg.type === "error";
          const isWarning =
            msg.type === "warning" || msg.type === "maintenance";

          let iconBg = "bg-blue-100 text-blue-600";
          let btnClass = "bg-blue-600 hover:bg-blue-700 text-white";
          let Icon = Info;

          if (isError) {
            iconBg = "bg-red-100 text-red-600";
            btnClass = "bg-red-600 hover:bg-red-700 text-white";
            Icon = AlertOctagon;
          } else if (isWarning) {
            iconBg = "bg-amber-100 text-amber-600";
            btnClass = "bg-amber-600 hover:bg-amber-700 text-white";
            Icon = AlertTriangle;
          }

          return (
            <div
              key={msg.id}
              className="relative overflow-hidden rounded-2xl bg-white shadow-2xl animate-in zoom-in-95 duration-300"
            >
              <div className="p-8 flex flex-col items-center text-center">
                <div
                  className={`flex items-center justify-center w-16 h-16 rounded-full mb-6 ${iconBg}`}
                >
                  <Icon className="w-8 h-8" strokeWidth={2} />
                </div>

                {msg.title && (
                  <h3 className="text-xl font-bold text-gray-900 mb-3">
                    {msg.title}
                  </h3>
                )}

                <p className="text-gray-600 text-base leading-relaxed whitespace-pre-wrap text-pretty">
                  {msg.message}
                </p>

                <button
                  onClick={() => handleDismiss(msg.id)}
                  className={`mt-8 w-full py-3 px-4 rounded-xl font-semibold transition shadow-sm active:scale-95 ${btnClass}`}
                >
                  Acknowledge
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
