import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { useState } from "react";
import { useWebSocketEvent } from "~/hooks/useWebSocket";

export async function loader() {
  try {
    // Fetch system info from backend
    const [healthRes, devicesRes, systemRes] = await Promise.all([
      fetch("http://localhost:8000/api/health"),
      fetch("http://localhost:8000/api/pm3/devices"),
      fetch("http://localhost:8000/api/system/info"),
    ]);

    const health = await healthRes.json();
    const devicesData = await devicesRes.json();
    const rawSystemInfo = await systemRes.json();

    // Extract devices array from response (API returns {devices: [...]} directly)
    const devices = devicesData.devices || [];

    // Flatten system info for easier access in UI
    const systemInfo = {
      hostname: rawSystemInfo.hostname,
      cpu_temp: rawSystemInfo.cpu_temp,
      cpu_per_core: rawSystemInfo.cpu?.per_core || [],
      load_average: rawSystemInfo.cpu?.load_average || null,
      memory_used: rawSystemInfo.memory_used,
      memory_total: rawSystemInfo.memory_total,
      disk_used: rawSystemInfo.disk_used,
      disk_total: rawSystemInfo.disk_total,
    };

    return json({ health, devices, systemInfo });
  } catch (error) {
    // Return mock data if backend is not available
    return json({
      health: { status: "unknown", version: "0.1.0" },
      devices: [],
      systemInfo: {
        hostname: "dangerous-pi",
        cpu_temp: null,
        cpu_per_core: [],
        load_average: null,
        memory_used: 0,
        memory_total: 0,
        disk_used: 0,
        disk_total: 0,
      },
    });
  }
}

interface SystemStats {
  cpu_percent: number;
  cpu_per_core: { core_id: number; percent: number; online?: boolean }[];
  load_average: number[];
  memory_percent: number;
  temperature: number | null;
}

interface PM3DeviceData {
  device_id: string;
  device_path: string;
  status: string;
  friendly_name: string;
  firmware_info?: { os_version?: string };
}

export default function Dashboard() {
  const loaderData = useLoaderData<typeof loader>();
  const [eventMessage, setEventMessage] = useState<string | null>(null);

  // Real-time state from WebSocket
  const [systemStats, setSystemStats] = useState<SystemStats | null>(null);
  const [pm3Devices, setPm3Devices] = useState<PM3DeviceData[] | null>(null);

  // Merge real-time data with loader data
  const data = {
    ...loaderData,
    systemInfo: {
      ...loaderData.systemInfo,
      ...(systemStats && {
        cpu_per_core: systemStats.cpu_per_core,
        load_average: systemStats.load_average,
        cpu_temp: systemStats.temperature ?? loaderData.systemInfo.cpu_temp,
      }),
    },
    devices: pm3Devices ?? loaderData.devices,
  };

  // WebSocket event subscriptions for real-time updates
  useWebSocketEvent("connected", (data) => {
    console.log("WebSocket connected:", data);
  });

  useWebSocketEvent("pm3_status", (data) => {
    setEventMessage(`PM3: ${data.message}`);
    setTimeout(() => setEventMessage(null), 5000);
  });

  // PM3 devices - real-time on connect/disconnect
  useWebSocketEvent("pm3_devices", (data) => {
    setPm3Devices(data.devices as PM3DeviceData[]);
  });

  // System stats - real-time every 5s from backend
  useWebSocketEvent("system_stats", (data) => {
    setSystemStats(data as SystemStats);
  });

  useWebSocketEvent("update_available", (data) => {
    setEventMessage(`Update available: ${data.version}`);
  });

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return "0 B";
    const k = 1024;
    const sizes = ["B", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
  };

  const memoryPercent = data.systemInfo.memory_total > 0
    ? ((data.systemInfo.memory_used / data.systemInfo.memory_total) * 100).toFixed(1)
    : "0";

  const diskPercent = data.systemInfo.disk_total > 0
    ? ((data.systemInfo.disk_used / data.systemInfo.disk_total) * 100).toFixed(1)
    : "0";

  return (
    <div className="container">
      <h1 style={{ marginBottom: "var(--space-6)" }}>
        <span style={{ color: "var(--color-primary)" }}>▸</span> Dashboard
      </h1>

      {eventMessage && (
        <div className="toast">
          <div style={{ display: "flex", alignItems: "center", gap: "var(--space-3)" }}>
            <span style={{ fontSize: "1.5rem" }}>●</span>
            <span>{eventMessage}</span>
          </div>
        </div>
      )}

      <div className="card-grid" style={{ marginBottom: "var(--space-6)" }}>
        {/* System Status */}
        <div className="card">
          <h3 className="card-title">
            <span style={{ color: "var(--color-primary)" }}>◈</span> System Status
          </h3>
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-3)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span className="text-secondary">Backend</span>
              <span className={`badge ${data.health.status === "healthy" ? "badge-success" : "badge-error"}`}>
                <span aria-hidden="true">●</span>
                {data.health.status}
              </span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span className="text-secondary">Hostname</span>
              <span className="text-primary">{data.systemInfo.hostname || "unknown"}</span>
            </div>
            {data.systemInfo.cpu_temp && (
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span className="text-secondary">CPU Temp</span>
                <span className={data.systemInfo.cpu_temp > 70 ? "text-warning" : "text-primary"}>
                  {data.systemInfo.cpu_temp.toFixed(1)}°C
                </span>
              </div>
            )}
            {/* CPU Load per Core */}
            {data.systemInfo.cpu_per_core && data.systemInfo.cpu_per_core.length > 0 && (
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--space-2)" }}>
                  <span className="text-secondary">CPU Cores</span>
                  {data.systemInfo.load_average && (
                    <span className="text-muted" style={{ fontSize: "0.75rem" }}>
                      Load: {data.systemInfo.load_average.map((l: number) => l.toFixed(2)).join(" / ")}
                    </span>
                  )}
                </div>
                <div style={{ display: "flex", gap: "var(--space-2)", flexWrap: "wrap" }}>
                  {data.systemInfo.cpu_per_core.map((core: { core_id: number; percent: number; online?: boolean }) => {
                    const isOnline = core.online !== false;
                    return (
                      <div
                        key={core.core_id}
                        className="cpu-core-bar"
                        style={{
                          flex: "1 1 auto",
                          minWidth: "50px",
                          textAlign: "center",
                          opacity: isOnline ? 1 : 0.4,
                        }}
                        title={isOnline ? `Core ${core.core_id}: ${core.percent.toFixed(0)}%` : `Core ${core.core_id}: Disabled`}
                      >
                        <div
                          style={{
                            height: "4px",
                            background: "var(--color-border)",
                            borderRadius: "2px",
                            overflow: "hidden",
                            marginBottom: "var(--space-1)",
                          }}
                        >
                          <div
                            style={{
                              height: "100%",
                              width: isOnline ? `${Math.min(100, core.percent)}%` : "0%",
                              background: !isOnline
                                ? "var(--color-text-muted)"
                                : core.percent > 80
                                ? "var(--color-error)"
                                : core.percent > 50
                                ? "var(--color-warning)"
                                : "var(--color-accent)",
                              transition: "width 0.3s ease",
                            }}
                          />
                        </div>
                        <span style={{
                          fontSize: "0.7rem",
                          fontFamily: "var(--font-mono)",
                          color: isOnline ? "inherit" : "var(--color-text-muted)",
                          textDecoration: isOnline ? "none" : "line-through",
                        }}>
                          C{core.core_id}: {isOnline ? `${core.percent.toFixed(0)}%` : "OFF"}
                        </span>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span className="text-secondary">Memory</span>
              <span className="text-primary">
                {formatBytes(data.systemInfo.memory_used)} / {formatBytes(data.systemInfo.memory_total)} ({memoryPercent}%)
              </span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span className="text-secondary">Disk</span>
              <span className="text-primary">
                {formatBytes(data.systemInfo.disk_used)} / {formatBytes(data.systemInfo.disk_total)} ({diskPercent}%)
              </span>
            </div>
          </div>
        </div>

        {/* PM3 Devices */}
        <div className="card">
          <h3 className="card-title">
            <span style={{ color: "var(--color-accent)" }}>▶</span> Proxmark3 Devices ({data.devices.length})
          </h3>

          {data.devices.length === 0 ? (
            <div style={{ textAlign: "center", padding: "var(--space-4)" }}>
              <div style={{ fontSize: "2rem", marginBottom: "var(--space-2)", opacity: 0.5 }}>🔌</div>
              <p className="text-secondary" style={{ marginBottom: "var(--space-1)" }}>
                No devices detected
              </p>
              <p className="text-muted" style={{ fontSize: "0.875rem" }}>
                Connect a Proxmark3 via USB
              </p>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-3)" }}>
              {data.devices.map((device: any) => {
                const isConnected = device.status === "connected";
                const isInUse = device.status === "in_use";
                const deviceName = device.friendly_name || device.device_path;

                return (
                  <div
                    key={device.device_id}
                    style={{
                      padding: "var(--space-3)",
                      background: "var(--color-bg)",
                      borderRadius: "var(--radius)",
                      border: "1px solid var(--color-border)",
                    }}
                  >
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--space-2)" }}>
                      <span style={{ fontWeight: 600, fontSize: "1rem" }}>{deviceName}</span>
                      <span
                        className={`badge ${
                          isConnected
                            ? "badge-success"
                            : isInUse
                            ? "badge-warning"
                            : "badge-error"
                        } badge-pulse`}
                      >
                        <span aria-hidden="true">●</span>
                        {isConnected ? "Connected" : isInUse ? "In Use" : device.status}
                      </span>
                    </div>

                    <div style={{ fontSize: "0.875rem", color: "var(--color-text-muted)" }}>
                      <div style={{ marginBottom: "var(--space-1)" }}>
                        <span style={{ fontFamily: "var(--font-mono)" }}>{device.device_path}</span>
                      </div>
                      {device.firmware_info && (
                        <div>
                          {device.firmware_info.os_version}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          <div style={{ marginTop: "var(--space-4)", display: "flex", gap: "var(--space-2)" }}>
            <a href="/commands" className="btn btn-primary" style={{ flex: 1 }}>
              {data.devices.length > 0 ? "Select Device & Start" : "Waiting for Device..."}
            </a>
          </div>
        </div>

        {/* Quick Actions */}
        <div className="card">
          <h3 className="card-title">
            <span style={{ color: "var(--color-secondary)" }}>⚡</span> Quick Actions
          </h3>
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-2)" }}>
            <a href="/commands?cmd=hf+search" className="btn btn-secondary" style={{ justifyContent: "flex-start" }}>
              <span>🔍</span>
              <span>HF Search</span>
            </a>
            <a href="/commands?cmd=lf+search" className="btn btn-secondary" style={{ justifyContent: "flex-start" }}>
              <span>🔍</span>
              <span>LF Search</span>
            </a>
            <a href="/commands?cmd=hw+tune" className="btn btn-secondary" style={{ justifyContent: "flex-start" }}>
              <span>📡</span>
              <span>Tune Antenna</span>
            </a>
            <a href="/settings" className="btn btn-secondary" style={{ justifyContent: "flex-start" }}>
              <span>⚙</span>
              <span>Settings</span>
            </a>
          </div>
        </div>
      </div>

      {/* Footer */}
      <div style={{ textAlign: "center", padding: "var(--space-6) 0", color: "var(--color-text-muted)" }}>
        <p>
          <strong style={{ color: "var(--color-primary)" }}>Dangerous Pi</strong> v{data.health.version}
        </p>
        <p style={{ fontSize: "0.875rem", marginTop: "var(--space-2)" }}>
          Built for <a href="https://dangerousthings.com" target="_blank" rel="noopener noreferrer">Dangerous Things</a>
        </p>
      </div>
    </div>
  );
}
