import { useEffect, useMemo, useState, type ReactNode } from "react";
import { WebsocketContext, type WebSocketConextValue } from "../context/WebSocketContext";
import useWebSocket from "react-use-websocket";
import { wsConfig } from "../config/wsconfig";
import type { CameraZoomData, InfoBarData } from "../../types/types";
import { CAMERA_IDS } from "../config/cameraConfig";
import { CAMBASE_WS } from "../../utils/config";
import { useCameraFeedContext } from "../context/CameraFeedContext";

type WebSocketProviderProps = {
  children: ReactNode;
};

export const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
  const { state } = useCameraFeedContext();
  const [systemData, setSystemData] = useState<InfoBarData | null>(null);
  const [socketData, setSocketData] = useState<CameraZoomData | null>(null);
  const infoSocket = useWebSocket(wsConfig.infoBar, { share: true, shouldReconnect: () => true });
  const sockets = CAMERA_IDS.reduce(
    (acc, id) => {
      acc[id] = `${CAMBASE_WS}/websocket-Camera${id}-live-video`;
      return acc;
    },
    {} as Record<string, string>,
  );
  const cameraFeedID = state.cameraFeedID;
  const cameraFeed = useWebSocket(sockets[cameraFeedID], { share: true, shouldReconnect: () => true });

  useEffect(() => {
    async function parseData() {
      if (infoSocket.lastMessage) {
        const text = await infoSocket.lastMessage.data.text();
        const data = JSON.parse(text);
        setSystemData(data);
      }
      if (cameraFeed.lastMessage) {
        const message = cameraFeed.lastMessage;
        const data = await message?.data.text();
        const parsedData: CameraZoomData = JSON.parse(data || "");
        setSocketData(parsedData);
      }
    }
    parseData();
  }, [cameraFeed.lastMessage, infoSocket.lastMessage]);

  const value = useMemo<WebSocketConextValue>(
    () => ({
      info: {
        data: systemData,
        readyState: infoSocket.readyState,
        sendJson: infoSocket.sendJsonMessage,
      },
      cameraFeed: {
        data: socketData,
        readyState: cameraFeed.readyState,

        send: cameraFeed.sendMessage,
      },
    }),
    [
      cameraFeed.readyState,
      cameraFeed.sendMessage,
      infoSocket.readyState,
      infoSocket.sendJsonMessage,
      socketData,
      systemData,
    ],
  );

  return <WebsocketContext.Provider value={value}>{children}</WebsocketContext.Provider>;
};
