import React, { useState, useRef, useEffect, useCallback } from 'react';
import './VolumeSlider.css'; // Keep the same CSS for now
import { useMixersContext } from '../../context/MixersContext';
import useFaderHelpers from '../../hooks/useFaderHelpers';

const SessionTrackGain = ({
  mixers,
  gainType,
  controlGroup,
  sessionController,
  orientation = 'vertical'
}) => {
  //console.debug("SessionTrackGain: Rendering for mixers", mixers, "gainType", gainType, "controlGroup", controlGroup);

  const mixerHelper = useMixersContext();
  const faderHelpers = useFaderHelpers();
  const [isDragging, setIsDragging] = useState(false);

  // Get the mixer to work with
  const getMixer = useCallback(() => {
    let mixer = mixers?.mixer;
    if (mixer && Array.isArray(mixer)) {
      mixer = mixer[0];
    }
    return mixer;
  }, [mixers]);

  // Initialize value from mixer
  const getInitialValue = useCallback(() => {
    const mixer = getMixer();
    if (mixer) {
      return faderHelpers.convertAudioTaperToPercent(mixer.volume_left);
    }
    return 50; // fallback
  }, [getMixer, faderHelpers]);

  const [currentValue, setCurrentValue] = useState(getInitialValue);

  // Update value when mixer changes
  useEffect(() => {
    const newValue = getInitialValue();
    setCurrentValue(newValue);
  }, [getInitialValue]);

  // Handle range input change
  const handleRangeChange = useCallback(async (e) => {
    const percentage = parseInt(e.target.value, 10);

    // Update the mixer - handle special cases like web version
    if (mixers) {
      let mixersToUpdate = mixers.mixer || mixers;

      // Handle special cases for media tracks, jam tracks, etc.
      // Similar to web version logic
      if (mixers.mixer && !Array.isArray(mixers.mixer)) {
        const mixer = mixers.mixer;
        // Check if this is a media track, jam track, or media category
        if (mixer.group_id === 3 || mixer.group_id === 4 ||  // MediaTrackGroup, JamTrackGroup
            ((mixer.group_id === 6 || mixer.group_id === 7) && mixer.name === 'MediaTrack')) { // MonitorCatGroup, MasterCatGroup with MediaTrack
          if (mixers.oppositeMixer) {
            mixersToUpdate = [mixer, mixers.oppositeMixer];
          }
        }
      }

      await mixerHelper.faderChanged(
        { percentage, dragging: isDragging },
        mixersToUpdate,
        gainType,
        controlGroup
      );
    }

    // Update local state
    setCurrentValue(percentage);
  }, [mixers, gainType, controlGroup, mixerHelper, isDragging]);

  // Handle input start (mousedown/touchstart equivalent)
  const handleInputStart = useCallback(() => {
    setIsDragging(true);
  }, []);

  // Handle input end (mouseup/touchend equivalent)
  const handleInputEnd = useCallback(() => {
    setIsDragging(false);
  }, []);

  return (
    <div>
      <div id="slider-value"><small>{getMixer()?.volume_left || 0}db</small></div>
      <div className={orientation === 'vertical' ? "vertical-slider-container" : "horizontal-slider-container"}>
        <input
          type="range"
          min="0"
          max="100"
          step="1"
          value={currentValue}
          onChange={handleRangeChange}
          onMouseDown={handleInputStart}
          onMouseUp={handleInputEnd}
          onTouchStart={handleInputStart}
          onTouchEnd={handleInputEnd}
          className={`slider-range ${orientation === 'horizontal' ? 'horizontal' : ''}`}
          orient={orientation === 'vertical' ? 'vertical' : undefined}
        />
      </div>
    </div>
  );
};

export default SessionTrackGain;
