import React, { useState, useEffect, memo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useMixersContext } from '../../context/MixersContext';
import { useJamClient } from '../../context/JamClientContext';
import usePanHelpers from '../../hooks/usePanHelpers';
import SessionTrackVU from './SessionTrackVU';
import SessionTrackGain from './SessionTrackGain';
import TrackDiagnostics from './TrackDiagnostics';
import JKSessionInstrumentModal from './JKSessionInstrumentModal';
import JKSessionPluginModal from './JKSessionPluginModal';
import JKSessionPanModal from './JKSessionPanModal';
import JKProfileSidePanel from '../profile/JKProfileSidePanel';
import { UncontrolledTooltip } from 'reactstrap';
import { getInstrumentName } from '../../helpers/utils';
import { getPersonById } from '../../helpers/rest';
import { ASSIGNMENT } from '../../helpers/globals';
import { selectSessionId, updateParticipantTrackInstrument, updateUserTrack } from '../../store/features/activeSessionSlice';
import { syncTracksToServer } from '../../services/trackSyncService';
import './JKSessionMyTrack.css';
import pluginIcon from '../../assets/img/client/plugin.svg';
import JKInstrumentIcon from '../profile/JKInstrumentIcon';

const JKSessionMyTrack = memo(function JKSessionMyTrack({
  track,
  mixers,
  hasMixer,
  name,
  trackName,
  instrument,
  photoUrl,
  clientId,
  userId,
  connStatsClientId,
  mode,
  isChat = false,
  isRemote = false,
  hideAvatar = false
}) {
  const dispatch = useDispatch();
  const sessionId = useSelector(selectSessionId);
  const mixerHelper = useMixersContext();
  const jamClient = useJamClient();
  const { convertPanToPercent } = usePanHelpers();
  const [pan, setPan] = useState(0);
  const [showMenu, setShowMenu] = useState(false);
  const [showDiagnostics, setShowDiagnostics] = useState(false);
  const [diagnosticsHoverCount, setDiagnosticsHoverCount] = useState(0);
  const [showInstrumentModal, setShowInstrumentModal] = useState(false);
  const [showPluginModal, setShowPluginModal] = useState(false);
  const [showPanModal, setShowPanModal] = useState(false);
  const [showProfilePanel, setShowProfilePanel] = useState(false);
  const [profileUser, setProfileUser] = useState(null);

  //console.log('JKSessionMyTrack instrumentIcon:', instrumentIcon);

  useEffect(() => {
    if (mixers?.mixer) {
      setPan(mixers.mixer.pan || 0);
    }
  }, [mixers]);

  const trackClasses = `session-track ${isChat ? 'chat-track' : 'my-track'} ${hasMixer ? 'has-mixer' : 'no-mixer'}`;

  const panStyle = {
    transform: `rotate(${pan}deg)`,
    WebkitTransform: `rotate(${pan}deg)`
  };

  // Connection state - only show for non-chat tracks
  const handleConnectionMouseEnter = () => {
    setDiagnosticsHoverCount(prev => prev + 1);
    setShowDiagnostics(true);
  };

  const handleConnectionMouseLeave = () => {
    setTimeout(() => {
      setDiagnosticsHoverCount(prev => {
        const newCount = prev - 1;
        if (newCount <= 0) {
          setShowDiagnostics(false);
        }
        return Math.max(0, newCount);
      });
    }, 100); // Small delay to prevent flickering
  };

  const handleDiagnosticsMouseEnter = () => {
    setDiagnosticsHoverCount(prev => prev + 1);
  };

  const handleDiagnosticsMouseLeave = () => {
    setTimeout(() => {
      setDiagnosticsHoverCount(prev => {
        const newCount = prev - 1;
        if (newCount <= 0) {
          setShowDiagnostics(false);
        }
        return Math.max(0, newCount);
      });
    }, 100); // Small delay to prevent flickering
  };

  const handleCloseDiagnostics = () => {
    setShowDiagnostics(false);
    setDiagnosticsHoverCount(0);
  };

  const connectionStateJsx = !isChat ? (
    <div
      className="track-connection-state unknown"
      onMouseEnter={handleConnectionMouseEnter}
      onMouseLeave={handleConnectionMouseLeave}
      onClick={() => setShowDiagnostics(!showDiagnostics)}
    />
  ) : null;

  const handleInstrumentClick = () => {
    setShowInstrumentModal(true);
  };

  const handleInstrumentSave = async instrumentId => {
    // For user's own track, use TRACK1
    await jamClient.TrackSetInstrument(ASSIGNMENT.TRACK1, instrumentId);

    // Update Redux state immediately so UI reflects the change
    if (clientId && track?.client_track_id) {
      // Update participant track (for UI display)
      dispatch(updateParticipantTrackInstrument({
        clientId,
        trackId: track.client_track_id,
        instrumentId
      }));
      // Also update userTracks (for server sync payload)
      dispatch(updateUserTrack({
        id: track.client_track_id,
        instrument_id: instrumentId
      }));
    }

    // Sync tracks to server after instrument change
    if (sessionId && clientId) {
      console.log('[Track Sync] Instrument changed, syncing tracks');
      dispatch(syncTracksToServer(sessionId, clientId));
    }

    setShowInstrumentModal(false);
  };

  const handleInstrumentModalClose = () => {
    setShowInstrumentModal(false);
  };

  const handleProfileClick = async () => {
    if (isRemote && userId) {
      // For remote tracks, fetch user data and show profile panel
      try {
        const response = await getPersonById(userId);
        const userData = await response.json();
        setProfileUser(userData);
        setShowProfilePanel(true);
      } catch (error) {
        console.error('Error fetching user profile:', error);
      }
    } else {
      // For local tracks, open profile page in new tab
      window.open('/profile', '_blank');
    }
  };

  return (
    <div className={trackClasses}>
      <div className="disabled-track-overlay" />
      <div className="session-track-contents">
        <div className="name" style={{ cursor: 'pointer' }} onClick={handleProfileClick}>
          {trackName}
        </div>
        <div
          className="track-avatar"
          style={{
            cursor: hideAvatar ? 'default' : 'pointer',
            visibility: hideAvatar ? 'hidden' : 'visible'
          }}
          onClick={hideAvatar ? undefined : handleProfileClick}
        >
          <img src={photoUrl} alt="avatar" height={190} />
        </div>
        <div
          className="track-instrument"
          id={`instrument-tooltip-${clientId}-${track?.client_track_id || 'chat'}`}
          onClick={!isRemote ? handleInstrumentClick : undefined}
          style={!isRemote ? { cursor: 'pointer' } : {}}
        >
          {/* <img src={instrumentIcon} alt="instrument" /> */}
          <JKInstrumentIcon instrumentId={instrument} instrumentName={instrument} />
          {!isRemote && track?.hasVst && (
            <img
              src={pluginIcon}
              alt="VST Plugin"
              style={{
                marginLeft: '8px',
                width: '16px',
                height: '16px',
                cursor: 'pointer',
                verticalAlign: 'bottom'
              }}
              onClick={e => {
                e.stopPropagation();
                setShowPluginModal(true);
              }}
              title="Open VST Plugin"
            />
          )}
        </div>
        {!isChat && (
          <UncontrolledTooltip
            placement="top"
            target={`instrument-tooltip-${clientId}-${track?.client_track_id || 'chat'}`}
            trigger="hover click"
          >
            {track?.instrument || 'Unknown Instrument'}
          </UncontrolledTooltip>
        )}
        <div className="track-controls">
          <div className="vu-and-gain" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <SessionTrackVU
              orientation="horizontal"
              lightCount={11}
              lightWidth={25}
              lightHeight={15}
              side="best"
              mixers={mixers}
            />
            <SessionTrackGain mixers={mixers?.mixer} gainType="track" controlGroup={null} orientation="vertical" />
          </div>
          <div className="track-buttons">
            <div className="track-menu-container">
              <div className="track-menu-button" onClick={() => setShowMenu(!showMenu)}>
                ...
              </div>
              {showMenu && (
                <div className="track-menu">
                  {isRemote ? (
                    <>
                      <div
                        onClick={() => {
                          setShowPanModal(true);
                          setShowMenu(false);
                        }}
                      >
                        Pan
                      </div>
                      <div
                        onClick={() => {
                          handleProfileClick();
                          setShowMenu(false);
                        }}
                      >
                        Musician
                      </div>
                    </>
                  ) : (
                    <>
                      <div
                        onClick={() => {
                          console.log('Audio configuration options coming soon');
                          setShowMenu(false);
                        }}
                      >
                        Configure
                      </div>
                      <div
                        onClick={() => {
                          setShowInstrumentModal(true);
                          setShowMenu(false);
                        }}
                      >
                        Instrument
                      </div>
                      <div
                        onClick={() => {
                          setShowPluginModal(true);
                          setShowMenu(false);
                        }}
                      >
                        Plugin
                      </div>
                    </>
                  )}
                </div>
              )}
            </div>
            <div className="connection-container">{connectionStateJsx}</div>
          </div>
          <br className="clearall" />
        </div>
        <br className="clearall" />
      </div>
      {showDiagnostics && (
        <TrackDiagnostics
          connStatsClientId={connStatsClientId}
          isVisible={showDiagnostics}
          participant={{ user: { name: name || 'User', possessive: 'Their' } }}
          onMouseEnter={handleDiagnosticsMouseEnter}
          onMouseLeave={handleDiagnosticsMouseLeave}
          onClose={handleCloseDiagnostics}
          myTrack={!isRemote}
        />
      )}
      {!isRemote && (
        <>
          <JKSessionInstrumentModal
            isOpen={showInstrumentModal}
            toggle={handleInstrumentModalClose}
            onSave={handleInstrumentSave}
          />
          <JKSessionPluginModal
            isOpen={showPluginModal}
            toggle={() => setShowPluginModal(false)}
            trackNumber={ASSIGNMENT.TRACK1}
          />
        </>
      )}

      {/* Pan Modal for Remote Tracks */}
      {isRemote && (
        <JKSessionPanModal
          isOpen={showPanModal}
          toggle={() => setShowPanModal(false)}
          mixers={mixers}
        />
      )}

      {/* Profile Side Panel for Remote Tracks */}
      {isRemote && (
        <JKProfileSidePanel
          show={showProfilePanel}
          setShow={setShowProfilePanel}
          user={profileUser}
          latencyData={null} // Could be enhanced to show latency data if available
        />
      )}
    </div>
  );
});

JKSessionMyTrack.displayName = 'JKSessionMyTrack';

export default JKSessionMyTrack;
