import { io, Socket } from "socket.io-client";
import { store } from "../store";
import {
  updateTelemetry,
  setTelemetryLoading,
  setTelemetryError,
} from "../store/telemetrySlice";
import { BmsState } from "@/constants/types";

const SERVER_URL =
  "http://dev.vec-tr.ai:8089/?dashboardId=deviceDashboardSocket&assetId=V16000868651064644504";
const TOKEN =
  "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2NCIsImFjdGlvbiI6ImF1dGgiLCJ0b2tlbi12ZXJzaW9uIjowLCJpYXQiOjE3NTE2MDgwNjIsImV4cCI6MTc1MTY5NDQ2Mn0.-46Br0jSPwOTvkcDBTI05GJ1GavaAOOli6LEgkvjj3c";

let socket: Socket | null = null;

export const initSocket = () => {
  store.dispatch(setTelemetryLoading());
  console.log("Initializing socket connection...");
  socket = io(SERVER_URL, {
    transports: ["websocket"],
    extraHeaders: {
      Authorization: `Bearer ${TOKEN}`,
      controllingServer: "http://dev.vec-tr.ai:8082",
    },
    reconnection: true,
  });

  socket.on("connect", () => {
    console.log("Socket connected:", socket?.id);
  });

  socket.on("connect_error", (error) => {
    console.error("Socket connection error:", error);
    store.dispatch(setTelemetryError("Socket connection failed"));
  });

  socket.on("disconnect", (reason) => {
    console.log("Socket disconnecteddddd", reason);
    store.dispatch(setTelemetryError("Socket disconnected: " + reason));
  });

  socket.on("dataUpdate", handleSocketData);
};

export const disconnectSocket = () => {
  if (socket) {
    socket.disconnect();
    console.log("Socket disconnected");
  }
};

const handleSocketData = (data: any) => {
  console.log("...");
  try {
    const SoH =
      data.dataSeries.assetData[0].bms[0].bmsSpecific.ivecSpecific.soh ?? null;
    const SoC = data?.dataSeries?.assetData?.[0]?.bms?.[0]?.batterySoc ?? null;
    const currentMode =
      data?.dataSeries?.assetData?.[0]?.bms?.[0]?.bmsSpecific?.ivecSpecific
        ?.ivecStatus?.currentMode ?? null;

    const gps = data?.dataSeries?.locationData?.gps ?? null;

    const totalDistance = data?.dataSeries?.systemData?.odoMeter ?? null;

    const lat = gps?.[1];
    const lon = gps?.[2];
    console.log("GPS Data:", lat, lon);
    let bms_state: BmsState | null = null;

    if (currentMode === 0) {
      bms_state = 0;
    } else if (currentMode === 1) {
      bms_state = -1;
    } else if (currentMode === 2) {
      bms_state = 1;
    }

    store.dispatch(
      updateTelemetry({
        SoH,
        SoC,
        chargingState: bms_state,
        lat,
        lon,
        loading: false,
        error: null,
        totalDistance,
      })
    );
  } catch (err) {
    console.error("Error handling socket data:", err);
    store.dispatch(setTelemetryError("Data parsing failed"));
  }
};
