import { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import api from "../api/client";
import useMqttWebSocket from "./useMqttWebSocket";

export default function MqttDashboard() {
  const [devices, setDevices] = useState([]);
  const [brokerConnected, setBrokerConnected] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [hoveredRow, setHoveredRow] = useState(null);
  const [liveEvents, setLiveEvents] = useState([]);
  const navigate = useNavigate();

  const fetchStatus = async () => {
    try {
      const data = await api.get("/mqtt/status");
      setDevices(data.devices || []);
      setBrokerConnected(data.broker_connected);
      setError("");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatus();
    const interval = setInterval(fetchStatus, 30000);
    return () => clearInterval(interval);
  }, []);

  const handleWsMessage = useCallback((data) => {
    setLiveEvents((prev) => [data, ...prev].slice(0, 50));
    // Update device status on heartbeat
    if (data.type === "status/heartbeat") {
      setDevices((prev) => {
        const existing = prev.find((d) => d.device_serial === data.device_serial);
        if (existing) {
          return prev.map((d) =>
            d.device_serial === data.device_serial
              ? { ...d, online: true, seconds_since_heartbeat: 0 }
              : d
          );
        }
        return prev;
      });
    }
  }, []);

  const { connected: wsConnected } = useMqttWebSocket({
    enabled: true,
    onMessage: handleWsMessage,
  });

  const sendPing = async (serial, e) => {
    e.stopPropagation();
    try {
      await api.post(`/mqtt/command/${serial}`, { cmd: "ping", contents: {} });
    } catch (err) {
      setError(err.message);
    }
  };

  const formatTime = (seconds) => {
    if (!seconds && seconds !== 0) return "Never";
    if (seconds < 60) return `${seconds}s ago`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
    return `${Math.floor(seconds / 86400)}d ago`;
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
          MQTT Dashboard
        </h1>
        <div className="flex items-center gap-3">
          <span className="flex items-center gap-2 text-sm" style={{ color: "var(--text-muted)" }}>
            <span
              className={`inline-block w-2.5 h-2.5 rounded-full ${brokerConnected ? "bg-green-500" : ""}`}
              style={!brokerConnected ? { backgroundColor: "var(--danger)" } : undefined}
            />
            Broker {brokerConnected ? "Connected" : "Disconnected"}
          </span>
          <span className="flex items-center gap-2 text-sm" style={{ color: "var(--text-muted)" }}>
            <span
              className={`inline-block w-2.5 h-2.5 rounded-full ${wsConnected ? "bg-green-500" : ""}`}
              style={!wsConnected ? { backgroundColor: "var(--border-primary)" } : undefined}
            />
            Live
          </span>
        </div>
      </div>

      {error && (
        <div
          className="text-sm rounded-md p-3 mb-4 border"
          style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
        >
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
      ) : devices.length === 0 ? (
        <div
          className="rounded-lg p-8 text-center text-sm border"
          style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
        >
          No devices have sent heartbeats yet. Devices will appear here once they connect to the MQTT broker.
        </div>
      ) : (
        <div
          className="rounded-lg overflow-hidden border mb-6"
          style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
        >
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
                  <th className="px-4 py-3 text-left font-medium w-10" style={{ color: "var(--text-secondary)" }}>Status</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Serial</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Device ID</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Firmware</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>IP Address</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Uptime</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Last Seen</th>
                  <th className="px-4 py-3 text-left font-medium w-32" style={{ color: "var(--text-secondary)" }}>Actions</th>
                </tr>
              </thead>
              <tbody>
                {devices.map((device, index) => (
                  <tr
                    key={device.device_serial}
                    className="cursor-pointer"
                    style={{
                      borderBottom: index < devices.length - 1 ? "1px solid var(--border-primary)" : "none",
                      backgroundColor: hoveredRow === device.device_serial ? "var(--bg-card-hover)" : "transparent",
                    }}
                    onMouseEnter={() => setHoveredRow(device.device_serial)}
                    onMouseLeave={() => setHoveredRow(null)}
                    onClick={() => navigate(`/mqtt/commands?device=${device.device_serial}`)}
                  >
                    <td className="px-4 py-3">
                      <span
                        className={`inline-block w-2.5 h-2.5 rounded-full ${device.online ? "bg-green-500" : ""}`}
                        style={!device.online ? { backgroundColor: "var(--border-primary)" } : undefined}
                        title={device.online ? "Online" : "Offline"}
                      />
                    </td>
                    <td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-heading)" }}>
                      {device.device_serial}
                    </td>
                    <td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-muted)" }}>
                      {device.last_heartbeat?.device_id || "-"}
                    </td>
                    <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
                      {device.last_heartbeat?.firmware_version ? `v${device.last_heartbeat.firmware_version}` : "-"}
                    </td>
                    <td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-primary)" }}>
                      {device.last_heartbeat?.ip_address || "-"}
                    </td>
                    <td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
                      {device.last_heartbeat?.uptime_display || "-"}
                    </td>
                    <td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
                      {formatTime(device.seconds_since_heartbeat)}
                    </td>
                    <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                      <div className="flex gap-2">
                        <button
                          onClick={(e) => sendPing(device.device_serial, e)}
                          className="hover:opacity-80 text-xs cursor-pointer"
                          style={{ color: "var(--text-link)" }}
                        >
                          Ping
                        </button>
                        <button
                          onClick={(e) => { e.stopPropagation(); navigate(`/mqtt/logs?device=${device.device_serial}`); }}
                          className="hover:opacity-80 text-xs cursor-pointer"
                          style={{ color: "var(--text-link)" }}
                        >
                          Logs
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Live Event Feed */}
      <div>
        <h2 className="text-lg font-semibold mb-3" style={{ color: "var(--text-heading)" }}>
          Live Feed
          {wsConnected && (
            <span className="ml-2 text-xs font-normal" style={{ color: "var(--text-muted)" }}>
              (streaming)
            </span>
          )}
        </h2>
        <div
          className="rounded-lg border overflow-hidden"
          style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
        >
          {liveEvents.length === 0 ? (
            <div className="p-6 text-center text-sm" style={{ color: "var(--text-muted)" }}>
              {wsConnected ? "Waiting for MQTT messages..." : "WebSocket not connected — live events will appear once connected."}
            </div>
          ) : (
            <div className="max-h-80 overflow-y-auto">
              <table className="w-full text-xs">
                <thead>
                  <tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
                    <th className="px-3 py-2 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Type</th>
                    <th className="px-3 py-2 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Device</th>
                    <th className="px-3 py-2 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Data</th>
                  </tr>
                </thead>
                <tbody>
                  {liveEvents.map((event, i) => (
                    <tr
                      key={i}
                      style={{ borderBottom: "1px solid var(--border-primary)" }}
                    >
                      <td className="px-3 py-2">
                        <span
                          className="px-1.5 py-0.5 rounded text-xs"
                          style={{
                            backgroundColor: event.type === "logs"
                              ? "var(--badge-blue-bg)"
                              : event.type === "status/heartbeat"
                              ? "var(--success-bg)"
                              : "var(--bg-primary)",
                            color: event.type === "logs"
                              ? "var(--badge-blue-text)"
                              : event.type === "status/heartbeat"
                              ? "var(--success-text)"
                              : "var(--text-secondary)",
                          }}
                        >
                          {event.type}
                        </span>
                      </td>
                      <td className="px-3 py-2 font-mono" style={{ color: "var(--text-muted)" }}>
                        {event.device_serial}
                      </td>
                      <td className="px-3 py-2" style={{ color: "var(--text-primary)" }}>
                        {event.type === "logs"
                          ? event.payload?.message || JSON.stringify(event.payload)
                          : event.type === "status/heartbeat"
                          ? `Uptime: ${event.payload?.payload?.timestamp || "?"} | IP: ${event.payload?.payload?.ip_address || "?"}`
                          : JSON.stringify(event.payload).substring(0, 120)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
