import { useEffect, useRef, useState } from "react";
import { DataNet } from "@sjs/sdk";

const CHANNEL = "demo.json.state";

export function StateSyncDemo({ apiKey }: { apiKey: string }) {
  const clientRef = useRef<DataNet | null>(null);
  const [mode, setMode] = useState("idle");
  const [enabled, setEnabled] = useState(true);
  const [position, setPosition] = useState({ x: 120, y: 84 });

  useEffect(() => {
    const client = new DataNet({
      apiKey,
      clientId: "react-state-demo",
      deviceName: "React State Demo",
    });

    clientRef.current = client;
    client.on("connect", () => console.log("react connected"));
    client.on("error", (err) => console.error(err));
    client.subscribe(CHANNEL, (data) => {
      const next = data as { mode?: string; enabled?: boolean; position?: { x?: number; y?: number } };
      if (next.mode) setMode(next.mode);
      if (typeof next.enabled === "boolean") setEnabled(next.enabled);
      if (next.position?.x != null && next.position?.y != null) {
        setPosition({ x: next.position.x, y: next.position.y });
      }
    });

    void client.connect();
    return () => client.disconnect();
  }, [apiKey]);

  function publishState(nextMode: string) {
    const payload = {
      mode: nextMode,
      enabled,
      position,
      source: "react-demo",
    };
    clientRef.current?.publish(CHANNEL, payload);
    setMode(nextMode);
  }

  return (
    <div>
      <h1>React state sync</h1>
      <p>Channel: {CHANNEL}</p>
      <p>Mode: {mode}</p>
      <p>Enabled: {enabled ? "true" : "false"}</p>
      <p>
        Position: {position.x}, {position.y}
      </p>
      <button onClick={() => publishState("active")}>Publish active</button>
      <button onClick={() => publishState("idle")}>Publish idle</button>
    </div>
  );
}
