/**
 * HeaderWidgets - Display status widgets in the header area
 *
 * Shows notifications from:
 * - System managers (UPS, PM3, Updates)
 * - Enabled plugins
 *
 * Supports:
 * - Multiple severity levels (info, warning, error, success)
 * - Dismissible widgets
 * - Action buttons
 * - Auto-expiry
 * - Real-time updates via WebSocket
 */
import { useState, useEffect, useCallback } from "react";
import { Link } from "@remix-run/react";
import { useWebSocketEvent } from "~/hooks/useWebSocket";

interface HeaderWidget {
  id: string;
  source: string;
  severity: "info" | "warning" | "error" | "success";
  message: string;
  dismissible: boolean;
  icon?: string;
  action_label?: string;
  action_url?: string;
  created_at: string;
  expires_at?: string;
}

interface HeaderWidgetsProps {
  apiBase?: string;
}

export function HeaderWidgets({ apiBase = "/api" }: HeaderWidgetsProps) {
  const [widgets, setWidgets] = useState<HeaderWidget[]>([]);
  const [loading, setLoading] = useState(true);

  // Fetch widgets from API
  const fetchWidgets = useCallback(async () => {
    try {
      const response = await fetch(`${apiBase}/system/widgets`);
      if (response.ok) {
        const data: HeaderWidget[] = await response.json();
        setWidgets(data);
      }
    } catch (error) {
      console.error("Failed to load widgets:", error);
    } finally {
      setLoading(false);
    }
  }, [apiBase]);

  // WebSocket event subscriptions for real-time updates
  useWebSocketEvent("widget_added", () => {
    // Refresh widgets when a new one is added
    fetchWidgets();
  });

  useWebSocketEvent("widget_removed", (data) => {
    // Remove widget from local state
    const widgetId = data.widget_id as string;
    setWidgets((prev) => prev.filter((w) => w.id !== widgetId));
  });

  // Initial fetch and periodic refresh (30s fallback)
  useEffect(() => {
    fetchWidgets();
    const interval = setInterval(fetchWidgets, 30000);
    return () => clearInterval(interval);
  }, [fetchWidgets]);

  // Dismiss a widget
  const dismissWidget = async (widgetId: string) => {
    try {
      const response = await fetch(`${apiBase}/system/widgets/${encodeURIComponent(widgetId)}/dismiss`, {
        method: "POST",
      });

      if (response.ok) {
        setWidgets((prev) => prev.filter((w) => w.id !== widgetId));
      }
    } catch (error) {
      console.error("Failed to dismiss widget:", error);
    }
  };

  // Don't render anything if loading or no widgets
  if (loading || widgets.length === 0) {
    return null;
  }

  return (
    <div className="header-widgets" role="region" aria-label="Notifications">
      {widgets.map((widget) => (
        <div
          key={widget.id}
          className={`widget widget-${widget.severity}`}
          role="alert"
          aria-live={widget.severity === "error" ? "assertive" : "polite"}
        >
          {widget.icon && (
            <span className="widget-icon" aria-hidden="true">
              {widget.icon}
            </span>
          )}

          <span className="widget-message">{widget.message}</span>

          {widget.action_url && widget.action_label && (
            <Link to={widget.action_url} className="widget-action">
              {widget.action_label}
            </Link>
          )}

          {widget.dismissible && (
            <button
              onClick={() => dismissWidget(widget.id)}
              className="widget-dismiss"
              aria-label={`Dismiss: ${widget.message}`}
              title="Dismiss"
            >
              <DismissIcon />
            </button>
          )}
        </div>
      ))}
    </div>
  );
}

function DismissIcon() {
  return (
    <svg
      className="dismiss-icon"
      viewBox="0 0 12 12"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      aria-hidden="true"
    >
      <path
        d="M2 2L10 10M10 2L2 10"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
      />
    </svg>
  );
}

export default HeaderWidgets;
