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

const QUICK_ACTIONS = [
  { label: "Ping", cmd: "ping", contents: {} },
  { label: "Report Status", cmd: "system_info", contents: { action: "report_status" } },
  { label: "Get Settings", cmd: "system_info", contents: { action: "get_full_settings" } },
  { label: "Network Info", cmd: "system_info", contents: { action: "network_info" } },
  { label: "Device Time", cmd: "system_info", contents: { action: "get_device_time" } },
  { label: "Clock Time", cmd: "system_info", contents: { action: "get_clock_time" } },
  { label: "Firmware Status", cmd: "system_info", contents: { action: "get_firmware_status" } },
  { label: "List Melodies", cmd: "file_manager", contents: { action: "list_melodies" } },
  { label: "Restart", cmd: "system", contents: { action: "restart" }, danger: true },
];

const STATUS_STYLES = {
  success: { bg: "var(--success-bg)", color: "var(--success-text)" },
  error: { bg: "var(--danger-bg)", color: "var(--danger-text)" },
  pending: { bg: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" },
  timeout: { bg: "var(--danger-bg)", color: "var(--danger-text)" },
};

export default function CommandPanel() {
  const [searchParams] = useSearchParams();
  const [devices, setDevices] = useState([]);
  const [selectedDevice, setSelectedDevice] = useState(searchParams.get("device") || "");
  const [customCmd, setCustomCmd] = useState("");
  const [customContents, setCustomContents] = useState("{}");
  const [commands, setCommands] = useState([]);
  const [commandsTotal, setCommandsTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const [lastResponse, setLastResponse] = useState(null);
  const [expandedCmd, setExpandedCmd] = useState(null);

  useEffect(() => {
    api.get("/devices").then((data) => {
      setDevices(data.devices || []);
      if (!selectedDevice && data.devices?.length > 0) {
        setSelectedDevice(data.devices[0].device_id || "");
      }
    }).catch(() => {});
  }, []);

  useEffect(() => {
    if (selectedDevice) fetchCommands();
  }, [selectedDevice]);

  const fetchCommands = async () => {
    setLoading(true);
    try {
      const data = await api.get(`/mqtt/commands/${selectedDevice}?limit=50`);
      setCommands(data.commands || []);
      setCommandsTotal(data.total || 0);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const sendCommand = async (cmd, contents) => {
    if (!selectedDevice) {
      setError("Select a device first");
      return;
    }
    setSending(true);
    setError("");
    setLastResponse(null);
    try {
      const result = await api.post(`/mqtt/command/${selectedDevice}`, { cmd, contents });
      setLastResponse(result);
      // Wait briefly then refresh commands to see response
      setTimeout(fetchCommands, 2000);
    } catch (err) {
      setError(err.message);
    } finally {
      setSending(false);
    }
  };

  const sendCustomCommand = () => {
    if (!customCmd.trim()) {
      setError("Enter a command name");
      return;
    }
    let parsed;
    try {
      parsed = JSON.parse(customContents);
    } catch {
      setError("Invalid JSON in contents");
      return;
    }
    sendCommand(customCmd.trim(), parsed);
  };

  const formatPayload = (jsonStr) => {
    if (!jsonStr) return null;
    try {
      return JSON.stringify(JSON.parse(jsonStr), null, 2);
    } catch {
      return jsonStr;
    }
  };

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6" style={{ color: "var(--text-heading)" }}>
        Command Panel
      </h1>

      {/* Device Selector */}
      <div className="mb-6">
        <label className="block text-sm mb-2" style={{ color: "var(--text-secondary)" }}>
          Target Device
        </label>
        <select
          value={selectedDevice}
          onChange={(e) => setSelectedDevice(e.target.value)}
          className="w-full max-w-md px-3 py-2 rounded-md text-sm border"
          style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)", borderColor: "var(--border-primary)" }}
        >
          <option value="">Select a device...</option>
          {devices.map((d) => (
            <option key={d.id} value={d.device_id}>
              {d.device_name || d.device_id} ({d.device_id})
            </option>
          ))}
        </select>
      </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>
      )}

      {/* Quick Actions */}
      <div
        className="rounded-lg border p-4 mb-6"
        style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
      >
        <h2 className="text-sm font-medium mb-3" style={{ color: "var(--text-heading)" }}>
          Quick Actions
        </h2>
        <div className="flex flex-wrap gap-2">
          {QUICK_ACTIONS.map((action) => (
            <button
              key={action.label}
              onClick={() => sendCommand(action.cmd, action.contents)}
              disabled={sending || !selectedDevice}
              className="px-3 py-1.5 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
              style={{
                backgroundColor: action.danger ? "var(--danger-btn)" : "var(--btn-primary)",
                color: "var(--text-white)",
              }}
            >
              {action.label}
            </button>
          ))}
        </div>
      </div>

      {/* Custom Command */}
      <div
        className="rounded-lg border p-4 mb-6"
        style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
      >
        <h2 className="text-sm font-medium mb-3" style={{ color: "var(--text-heading)" }}>
          Custom Command
        </h2>
        <div className="flex flex-col gap-3">
          <div>
            <label className="block text-xs mb-1" style={{ color: "var(--text-muted)" }}>
              Command (cmd)
            </label>
            <input
              type="text"
              value={customCmd}
              onChange={(e) => setCustomCmd(e.target.value)}
              placeholder="e.g. system_info"
              className="w-full max-w-md px-3 py-2 rounded-md text-sm border"
            />
          </div>
          <div>
            <label className="block text-xs mb-1" style={{ color: "var(--text-muted)" }}>
              Contents (JSON)
            </label>
            <textarea
              value={customContents}
              onChange={(e) => setCustomContents(e.target.value)}
              rows={4}
              className="w-full max-w-md px-3 py-2 rounded-md text-sm border font-mono"
              style={{ resize: "vertical" }}
            />
          </div>
          <div>
            <button
              onClick={sendCustomCommand}
              disabled={sending || !selectedDevice}
              className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
            >
              {sending ? "Sending..." : "Send Command"}
            </button>
          </div>
        </div>
      </div>

      {/* Last Response */}
      {lastResponse && (
        <div
          className="rounded-lg border p-4 mb-6"
          style={{
            backgroundColor: lastResponse.success ? "var(--success-bg)" : "var(--danger-bg)",
            borderColor: lastResponse.success ? "var(--success)" : "var(--danger)",
          }}
        >
          <p className="text-sm" style={{ color: lastResponse.success ? "var(--success-text)" : "var(--danger-text)" }}>
            {lastResponse.message}
          </p>
        </div>
      )}

      {/* Command History */}
      {selectedDevice && (
        <div>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-lg font-semibold" style={{ color: "var(--text-heading)" }}>
              Command History
            </h2>
            <div className="flex items-center gap-3">
              <span className="text-sm" style={{ color: "var(--text-muted)" }}>
                {commandsTotal} commands
              </span>
              <button
                onClick={fetchCommands}
                className="text-sm hover:opacity-80 cursor-pointer"
                style={{ color: "var(--text-link)" }}
              >
                Refresh
              </button>
            </div>
          </div>

          {loading ? (
            <div className="text-center py-4" style={{ color: "var(--text-muted)" }}>Loading...</div>
          ) : commands.length === 0 ? (
            <div
              className="rounded-lg p-6 text-center text-sm border"
              style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
            >
              No commands sent to this device yet.
            </div>
          ) : (
            <div
              className="rounded-lg overflow-hidden border"
              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" style={{ color: "var(--text-secondary)" }}>Time</th>
                      <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Command</th>
                      <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Status</th>
                      <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Details</th>
                    </tr>
                  </thead>
                  <tbody>
                    {commands.map((cmd, index) => {
                      const style = STATUS_STYLES[cmd.status] || STATUS_STYLES.pending;
                      const isExpanded = expandedCmd === cmd.id;
                      return (
                        <>
                          <tr
                            key={cmd.id}
                            className="cursor-pointer"
                            style={{
                              borderBottom: (!isExpanded && index < commands.length - 1)
                                ? "1px solid var(--border-primary)" : "none",
                            }}
                            onClick={() => setExpandedCmd(isExpanded ? null : cmd.id)}
                          >
                            <td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
                              {cmd.sent_at?.replace("T", " ").substring(0, 19)}
                            </td>
                            <td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-heading)" }}>
                              {cmd.command_name}
                            </td>
                            <td className="px-4 py-3">
                              <span
                                className="px-2 py-0.5 text-xs rounded-full"
                                style={{ backgroundColor: style.bg, color: style.color }}
                              >
                                {cmd.status}
                              </span>
                            </td>
                            <td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
                              {cmd.responded_at ? `Replied ${cmd.responded_at.replace("T", " ").substring(0, 19)}` : "Awaiting response..."}
                            </td>
                          </tr>
                          {isExpanded && (
                            <tr key={`${cmd.id}-detail`} style={{ borderBottom: index < commands.length - 1 ? "1px solid var(--border-primary)" : "none" }}>
                              <td colSpan={4} className="px-4 py-3" style={{ backgroundColor: "var(--bg-primary)" }}>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                  <div>
                                    <p className="text-xs font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
                                      Sent Payload
                                    </p>
                                    <pre
                                      className="text-xs p-2 rounded overflow-auto max-h-48 font-mono"
                                      style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)" }}
                                    >
                                      {formatPayload(cmd.command_payload) || "—"}
                                    </pre>
                                  </div>
                                  <div>
                                    <p className="text-xs font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
                                      Response
                                    </p>
                                    <pre
                                      className="text-xs p-2 rounded overflow-auto max-h-48 font-mono"
                                      style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)" }}
                                    >
                                      {formatPayload(cmd.response_payload) || "Waiting..."}
                                    </pre>
                                  </div>
                                </div>
                              </td>
                            </tr>
                          )}
                        </>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
