/**
 * PowerWidget - Header battery/power status indicator
 *
 * Displays UPS/battery status in the header with:
 * - Battery icon with fill level
 * - Percentage display
 * - Charging indicator
 * - Real-time updates via WebSocket
 */
import { useState, useEffect, useCallback } from "react";
import { useWebSocketEvent } from "~/hooks/useWebSocket";

interface UPSStatus {
  battery_percentage: number;
  voltage: number;
  current: number;
  power_source: "ac" | "battery" | "unknown";
  battery_status: "charging" | "discharging" | "full" | "critical" | "unknown";
  time_remaining: number | null;
  temperature: number | null;
  last_updated: string | null;
  is_available: boolean;
  error_message: string | null;
}

interface PowerWidgetProps {
  apiBase?: string;
}

export function PowerWidget({ apiBase = "/api" }: PowerWidgetProps) {
  const [status, setStatus] = useState<UPSStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch UPS status from API
  const fetchStatus = useCallback(async () => {
    try {
      const response = await fetch(`${apiBase}/system/ups/status`);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      const data: UPSStatus = await response.json();
      setStatus(data);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch");
    } finally {
      setLoading(false);
    }
  }, [apiBase]);

  // WebSocket event subscriptions for real-time updates
  useWebSocketEvent("ups_battery", (data) => {
    setStatus((prev) => prev ? {
      ...prev,
      battery_percentage: data.percentage as number,
      voltage: data.voltage as number,
    } : prev);
  });

  useWebSocketEvent("ups_warning", () => {
    // Trigger a full refresh on warnings
    fetchStatus();
  });

  useWebSocketEvent("ups_critical", () => {
    fetchStatus();
  });

  // Initial fetch and fallback polling (120s since WebSocket is primary)
  useEffect(() => {
    fetchStatus();
    const pollInterval = setInterval(fetchStatus, 120000);
    return () => clearInterval(pollInterval);
  }, [fetchStatus]);

  // Don't render if UPS is not available
  if (!loading && (!status || !status.is_available)) {
    return null;
  }

  // Loading state
  if (loading) {
    return (
      <div className="power-widget power-widget--loading" title="Loading power status...">
        <div className="power-widget__icon">
          <BatteryIcon percentage={50} />
        </div>
      </div>
    );
  }

  const percentage = Math.round(status?.battery_percentage ?? 0);
  const isCharging = status?.power_source === "ac" || status?.battery_status === "charging";
  const isCritical = percentage <= 10;
  const isLow = percentage <= 20;
  const isFull = percentage >= 95 && isCharging;

  // Determine status color
  let statusClass = "power-widget--normal";
  if (isCritical) {
    statusClass = "power-widget--critical";
  } else if (isLow) {
    statusClass = "power-widget--low";
  } else if (isFull) {
    statusClass = "power-widget--full";
  } else if (isCharging) {
    statusClass = "power-widget--charging";
  }

  // Build tooltip
  const tooltipParts = [
    `Battery: ${percentage}%`,
    `Source: ${status?.power_source === "ac" ? "AC Power" : "Battery"}`,
  ];
  if (status?.voltage && status.voltage > 0) {
    // Voltage comes in mV from API, convert to V for display
    tooltipParts.push(`Voltage: ${(status.voltage / 1000).toFixed(2)}V`);
  }
  if (status?.current !== undefined && status?.current !== null) {
    // Current in Amps - positive = charging, negative = discharging
    const absCurrentMa = Math.abs(status.current * 1000).toFixed(0);
    const direction = status.current >= 0 ? "charging" : "draw";
    tooltipParts.push(`Current: ${absCurrentMa}mA ${direction}`);
  }
  if (status?.time_remaining) {
    // Format time remaining nicely
    const mins = status.time_remaining;
    if (mins < 60) {
      tooltipParts.push(`Est. runtime: ${mins} min`);
    } else {
      const hours = Math.floor(mins / 60);
      const remainMins = mins % 60;
      tooltipParts.push(`Est. runtime: ${hours}h ${remainMins}m`);
    }
  }
  const tooltip = tooltipParts.join("\n");

  return (
    <div
      className={`power-widget ${statusClass}`}
      title={tooltip}
      role="status"
      aria-label={`Battery at ${percentage}%${isCharging ? ", plugged in" : ", on battery"}`}
    >
      <div className="power-widget__icon">
        <BatteryIcon percentage={percentage} isCharging={isCharging} />
      </div>
      <span className="power-widget__percentage">{percentage}%</span>
      {isCharging && (
        <span className="power-widget__plug-indicator" aria-label="Plugged in" title="AC Power">
          <PlugIcon />
        </span>
      )}
    </div>
  );
}

interface BatteryIconProps {
  percentage: number;
  isCharging?: boolean;
}

function BatteryIcon({ percentage, isCharging = false }: BatteryIconProps) {
  // Calculate fill width (0-100%)
  const fillWidth = Math.max(0, Math.min(100, percentage));

  return (
    <svg
      className="battery-icon"
      viewBox="0 0 24 14"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      aria-hidden="true"
    >
      {/* Battery body outline */}
      <rect
        x="0.5"
        y="0.5"
        width="20"
        height="13"
        rx="2"
        stroke="currentColor"
        strokeWidth="1"
        fill="none"
      />

      {/* Battery terminal */}
      <rect
        x="21"
        y="4"
        width="3"
        height="6"
        rx="1"
        fill="currentColor"
      />

      {/* Battery fill */}
      <rect
        className="battery-icon__fill"
        x="2"
        y="2"
        width={Math.max(0, (fillWidth / 100) * 17)}
        height="10"
        rx="1"
        fill="currentColor"
      />

      {/* Charging bolt */}
      {isCharging && (
        <path
          className="battery-icon__bolt"
          d="M12 1L8 7H11L9 13L14 6H11L12 1Z"
          fill="var(--color-bg)"
          stroke="currentColor"
          strokeWidth="0.5"
        />
      )}
    </svg>
  );
}

function PlugIcon() {
  return (
    <svg
      className="plug-icon"
      viewBox="0 0 12 12"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      aria-hidden="true"
    >
      {/* Plug prongs */}
      <rect x="3" y="0" width="2" height="4" rx="0.5" fill="currentColor" />
      <rect x="7" y="0" width="2" height="4" rx="0.5" fill="currentColor" />
      {/* Plug body */}
      <rect x="2" y="3" width="8" height="5" rx="1" fill="currentColor" />
      {/* Cord */}
      <rect x="5" y="8" width="2" height="4" rx="0.5" fill="currentColor" />
    </svg>
  );
}

export default PowerWidget;
