import React from "react";
import { JsonView, darkStyles } from "react-json-view-lite";
import "react-json-view-lite/dist/index.css";
import { type WsMessage } from "../api/WsApi";
import { useUserInfo } from "../widgets/dashboard/BaseAuthenticatedPage";
import { MatrixGWRouteContainer } from "../widgets/MatrixGWRouteContainer";
import { MatrixWS, WSState } from "../widgets/messages/MatrixWS";
import { NotLinkedAccountMessage } from "../widgets/NotLinkedAccountMessage";

type TimestampedMessages = WsMessage & { time: number };

export function WSDebugRoute(): React.ReactElement {
  const user = useUserInfo();

  const [state, setState] = React.useState<string>(WSState.Closed);
  const [messages, setMessages] = React.useState<TimestampedMessages[]>([]);

  const handleMessage = (msg: WsMessage) => {
    setMessages((l) => [...l, msg]);
  };

  if (!user.info.matrix_account_connected) return <NotLinkedAccountMessage />;

  return (
    <MatrixGWRouteContainer label={"WebSocket Debug"}>
      {/* Status bar */}
      <div style={{ display: "flex", alignItems: "center" }}>
        <span style={{ marginRight: "0.5em" }}>State: </span>
        <span
          style={{
            marginRight: "0.5em",
            color: state == WSState.Connected ? "green" : "red",
          }}
        >
          {state}
        </span>
        <MatrixWS onStateChange={setState} onMessage={handleMessage} />
      </div>

      {/* WS messages list */}
      {messages.map((msg, id) => (
        <div style={{ margin: "10px", backgroundColor: "black" }}>
          <JsonView
            key={id}
            data={msg}
            shouldExpandNode={(level) => level < 2}
            style={{
              ...darkStyles,
              container: "",
            }}
          />
        </div>
      ))}
    </MatrixGWRouteContainer>
  );
}
