import React, { useEffect, useState, useCallback, memo } from 'react';
import {
  Modal,
  ModalHeader,
  ModalBody,
} from 'reactstrap';
import SessionTrackVU from './SessionTrackVU';
import SessionTrackGain from './SessionTrackGain'
import { useMixersContext } from '../../context/MixersContext';
import { useJamClient } from '../../context/JamClientContext';
import { MIX_MODES, ChannelGroupIds, CategoryGroupIds } from '../../helpers/globals.js';

const JKSessionVolumeModal = memo(function JKSessionVolumeModal({ isOpen, toggle }) {
  const mixerHelper = useMixersContext();
  const jamClient = useJamClient();
  const mixers = mixerHelper.myTracks[0]?.mixers;

  // Local state for fresh mixer data from native client
  const [musicMixer, setMusicMixer] = useState(null);
  const [chatMixer, setChatMixer] = useState(null);

  // Refresh mixer data from native client when modal opens
  // This ensures we have the latest values, including changes made in legacy app
  useEffect(() => {
    if (isOpen && jamClient) {
      const refreshMixers = async () => {
        try {
          // Get fresh mixer data from native client (PERSONAL mode for monitor output)
          const freshMixers = await jamClient.SessionGetAllControlState(false);

          // Find music and chat category mixers from fresh data
          // Category mixers are in MonitorCatGroup (group_id 3) with specific name properties
          for (const mixer of freshMixers) {
            if (mixer.group_id === ChannelGroupIds.MonitorCatGroup) {
              if (mixer.name === CategoryGroupIds.AudioInputMusic) {
                setMusicMixer(mixer);
              } else if (mixer.name === CategoryGroupIds.AudioInputChat) {
                setChatMixer(mixer);
              }
            }
          }
        } catch (error) {
          console.warn('Failed to refresh mixer data:', error);
        }
      };
      refreshMixers();
    }
  }, [isOpen, jamClient]);

  // Get music category mixer - prefer fresh data from state, fallback to context
  const getMusicMixers = useCallback(() => {
    if (musicMixer) {
      return musicMixer;
    }
    // Fallback to context data
    const categoryMixerResult = mixerHelper.getAudioInputCategoryMixer(MIX_MODES.PERSONAL);
    if (categoryMixerResult && categoryMixerResult.mixer) {
      return categoryMixerResult.mixer;
    }
    return null;
  }, [musicMixer, mixerHelper]);

  // Get chat category mixer - prefer fresh data from state, fallback to context
  const getChatMixers = useCallback(() => {
    if (chatMixer) {
      return chatMixer;
    }
    // Fallback to context data
    const categoryMixerResult = mixerHelper.getChatCategoryMixer(MIX_MODES.PERSONAL);
    if (categoryMixerResult && categoryMixerResult.mixer) {
      return categoryMixerResult.mixer;
    }
    return null;
  }, [chatMixer, mixerHelper]);

  const handleCancel = () => {
    // Volume changes are applied immediately via setSessionMixerCategoryPlayoutState
    // when the slider is moved, so no explicit save is needed here.
    // Note: FTUESave was removed because it was causing VU meters to stop working.
    toggle();
  };

  return (
    <Modal isOpen={isOpen} toggle={handleCancel} modalClassName="theme-modal" contentClassName="border" size="md">
      <ModalHeader toggle={handleCancel} className="bg-light d-flex flex-between-center border-bottom-0">
        Volume
      </ModalHeader>
      <ModalBody>
        <div className='d-flex' style={{ paddingRight: '0px', marginLeft: '0px' }}>

          <div style={{ borderRight: '1px #ddd solid', marginRight: '1rem' }}>
            <h6>Music Volume</h6>
            <div className='d-flex'>
              <div className='mr-2'>
                <SessionTrackGain mixers={getMusicMixers()} gainType="music" controlGroup="music" />
              </div>

              <div className='mr-2 d-flex'>
                <div className='mr-1'>
                  <SessionTrackVU mixers={mixers} lightCount={15} />
                </div>
                <div>
                  <SessionTrackVU mixers={mixers} lightCount={15} />
                </div>
              </div>

              <div className='pr-1'>
                <small className="d-block">Use this slider to control the volume of all the music in your session mix.</small>
                <small className="d-block">This will not affect the volume for other musicians in the session.</small>
              </div>
            </div>
          </div>

          <div>
            <h6>Chat Volume</h6>
            <div>
              <div className='d-flex'>
                <div className='mr-2'>
                  <SessionTrackGain mixers={getChatMixers()} gainType="chat" controlGroup="chat" />
                </div>

                <div className='mr-2 d-flex'>
                  <div className='mr-1'>
                    <SessionTrackVU mixers={mixers} lightCount={15} />
                  </div>
                  <div>
                    <SessionTrackVU mixers={mixers} lightCount={15} />
                  </div>
                </div>

                <div>
                  <small className="d-block">Use this slider to control the volume of all the music in your session mix.</small>
                  <small className="d-block">This will not affect the volume for other musicians in the session.</small>
                </div>
              </div>
            </div>
          </div>

        </div>

      </ModalBody>
    </Modal>
  );
});

JKSessionVolumeModal.displayName = 'JKSessionVolumeModal';

export default JKSessionVolumeModal;
