import { useCallback, useRef } from 'react';
import { useJamClient } from '../context/JamClientContext';
import { getSession } from '../helpers/rest';
import { LATENCY } from '../helpers/globals';

// Latency constants
// export const LATENCY = {
//   ME: { description: "ME", style: "latency-me", min: -1, max: -1 },
//   GOOD: { description: "GOOD", style: "latency-good", min: 0.0, max: 40.0 },
//   MEDIUM: { description: "FAIR", style: "latency-fair", min: 40.0, max: 70.0 },
//   POOR: { description: "HIGH", style: "latency-poor", min: 70.0, max: 100 },
//   UNACCEPTABLE: { description: "HIGH", style: "latency-poor", min: 100, max: 10000000 },
//   UNKNOWN: { description: "UNKNOWN", style: "latency-unknown", min: -2, max: -2 },
//   FAILED: { description: "N/A", style: "latency-failed", min: -3, max: -3 }
// };

export default function useSessionUtils() {
  const jamClient = useJamClient();
  const logger = console; // Replace with your logging mechanism if needed
  const autoOpenJamTrackRef = useRef(null);

  // Auto-open jam track functionality
  const setAutoOpenJamTrack = useCallback((jamTrack) => {
    logger.debug("setting auto-load jamtrack", jamTrack);
    autoOpenJamTrackRef.current = jamTrack;
  }, [logger]);

  const grabAutoOpenJamTrack = useCallback(() => {
    const jamTrack = autoOpenJamTrackRef.current;
    autoOpenJamTrackRef.current = null;
    logger.debug("grabbing auto-load jamtrack", jamTrack);
    return jamTrack;
  }, [logger]);

  // Latency data structure conversion
  const changeLatencyDataStructure = useCallback((data) => {
    return {
      id: data.user_id,
      audio_latency: data.audio_latency,
      full_score: data.ars['total_latency'],
      internet_score: data.ars['internet_latency']
    };
  }, []);

  // Score info calculation
  const scoreInfo = useCallback((userSession, isSameUser) => {
    const full_score = userSession.full_score;
    const internet_score = parseInt(userSession.internet_score);
    const audio_latency = parseInt(userSession.audio_latency);

    let latencyDescription;
    let latencyStyle;
    let iconName;
    let description;
    let latencyInfo;

    if (isSameUser) {
      latencyDescription = LATENCY.ME.description;
      latencyStyle = LATENCY.ME.style;
      iconName = 'purple';
      description = 'me';
      latencyInfo = '';
    } else if (full_score <= LATENCY.FAILED.max) {
      latencyDescription = LATENCY.FAILED.description;
      latencyStyle = LATENCY.FAILED.style;
      iconName = 'gray';
      description = 'failed';
      latencyInfo = '';
    } else if (!full_score || full_score <= LATENCY.UNKNOWN.max) {
      latencyDescription = LATENCY.UNKNOWN.description;
      latencyStyle = LATENCY.UNKNOWN.style;
      iconName = 'purple';
      description = 'missing';
      latencyInfo = '';
    } else if (full_score <= LATENCY.GOOD.max) {
      latencyDescription = LATENCY.GOOD.description;
      latencyStyle = LATENCY.GOOD.style;
      iconName = 'green';
      description = 'good';
      latencyInfo = 'Internet ' + internet_score + 'ms + Audio ' + audio_latency + 'ms';
    } else if (full_score <= LATENCY.MEDIUM.max) {
      latencyDescription = LATENCY.MEDIUM.description;
      latencyStyle = LATENCY.MEDIUM.style;
      iconName = 'yellow';
      description = 'fair';
      latencyInfo = 'Internet ' + internet_score + 'ms + Audio ' + audio_latency + 'ms';
    } else if (full_score <= LATENCY.POOR.max) {
      latencyDescription = LATENCY.POOR.description;
      latencyStyle = LATENCY.POOR.style;
      iconName = 'red';
      description = 'poor';
      latencyInfo = 'Internet ' + internet_score + 'ms + Audio ' + audio_latency + 'ms';
    } else if (full_score > LATENCY.UNACCEPTABLE.min) {
      latencyStyle = LATENCY.UNACCEPTABLE.style;
      latencyDescription = LATENCY.UNACCEPTABLE.description;
      iconName = 'blue';
      description = 'unacceptable';
      latencyInfo = 'Internet ' + internet_score + 'ms + Audio ' + audio_latency + 'ms';
    }

    return {
      latency_style: latencyStyle,
      latency_text: latencyDescription,
      icon_name: iconName,
      description: description,
      latency_info: latencyInfo
    };
  }, []);

  // Create latency info
  const createLatency = useCallback((userLatency) => {
    // Note: In React, we don't have access to currentUserId in the same way
    // This would need to be passed as a parameter or from context
    const isSameUser = userLatency.id === window.JK?.currentUserId; // Fallback for now
    return scoreInfo(userLatency, isSameUser);
  }, [scoreInfo]);

  // Clear audio timeout
  const clearAudioTimeout = useCallback(() => {
    if (window.JK?.AudioStopTimeout) {
      clearTimeout(window.JK.AudioStopTimeout);
      window.JK.AudioStopTimeout = null;
    }
  }, []);

  // FTUE functions
  const FTUEPageEnter = useCallback(async () => {
    logger.debug("sessionUtils: FTUEPageEnter");
    clearAudioTimeout();
    if (jamClient?.FTUEPageEnter) {
      await jamClient.FTUEPageEnter();
    }
  }, [jamClient, logger, clearAudioTimeout]);

  const FTUEPageLeave = useCallback(async () => {
    logger.debug("sessionUtils: FTUEPageLeave");
    clearAudioTimeout();
    if (jamClient?.FTUEPageLeave) {
      await jamClient.FTUEPageLeave();
    }
  }, [jamClient, logger, clearAudioTimeout]);

  const SessionPageEnter = useCallback(async () => {
    logger.debug("sessionUtils: SessionPageEnter");
    clearAudioTimeout();
    if (jamClient?.SessionPageEnter) {
      return await jamClient.SessionPageEnter();
    }
  }, [jamClient, logger, clearAudioTimeout]);

  const SessionPageLeave = useCallback(async () => {
    logger.debug("sessionUtils: SessionPageLeave");
    clearAudioTimeout();
    if (jamClient?.SessionPageLeave) {
      await jamClient.SessionPageLeave();
    }
  }, [jamClient, logger, clearAudioTimeout]);

  // Join session from custom URL scheme
  const joinSessionFromCustomUrlScheme = useCallback((hash) => {
    const qStr = hash.substring(hash.lastIndexOf('/') + 1);
    const qParamsArr = qStr.split('|');
    let isCustom = undefined;
    let sessionId = undefined;

    qParamsArr.forEach((q) => {
      const qp = q.split('~');
      if (qp[0] === 'custom') {
        isCustom = qp[1];
      }
      if (qp[0] === 'sessionId') {
        sessionId = qp[1];
      }
    });

    if (!isCustom || isCustom !== 'yes') {
      return;
    }
    if (!sessionId) {
      return;
    }

    // Note: joinSession implementation would need to be provided
    // For now, just log
    logger.debug("Would join session from custom URL:", sessionId);
  }, [logger]);

  return {
    // Auto-open jam track
    setAutoOpenJamTrack,
    grabAutoOpenJamTrack,

    // Latency utilities
    changeLatencyDataStructure,
    scoreInfo,
    createLatency,

    // FTUE functions
    FTUEPageEnter,
    FTUEPageLeave,
    SessionPageEnter,
    SessionPageLeave,

    // URL scheme handling
    joinSessionFromCustomUrlScheme,

    // Constants
    LATENCY
  };
}
