import React, { useState, useRef, useEffect, useContext } from 'react';
import { createPortal } from 'react-dom';
import { useJamClient } from '../../context/JamClientContext';
import { useAuth } from '../../context/UserAuth';
import { toast } from 'react-toastify';
import openIcon from '../../assets/img/client/open.svg';

const JKSessionOpenMenu = ({
  onBackingTrackSelected,
  onJamTrackSelected,
  onMetronomeSelected,
  isBackingTrackOpen = false,
  isJamTrackOpen = false,
  isMetronomeOpen = false
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const buttonRef = useRef(null);
  const menuRef = useRef(null);
  const jamClient = useJamClient();

  // Check if any media player is currently open
  const isAnyMediaOpen = isBackingTrackOpen || isJamTrackOpen || isMetronomeOpen;

  // Get the name of currently open media for tooltip/message
  const getOpenMediaName = () => {
    if (isBackingTrackOpen) return 'Backing Track';
    if (isJamTrackOpen) return 'JamTrack';
    if (isMetronomeOpen) return 'Metronome';
    return null;
  };

  const toggle = () => setIsOpen(prev => !prev);

  const handleMenuItemClick = async (item) => {
    console.log(`Selected: ${item}`);
    setIsOpen(false);

    // Check if any media is already open - prevent opening another
    if (isAnyMediaOpen) {
      const openMediaName = getOpenMediaName();
      toast.warning(`Please close the ${openMediaName} before opening another media.`);
      return;
    }

    if (item === 'JamTracks') {
      if (onJamTrackSelected) {
        onJamTrackSelected();
      }
    } else if (item === 'Backing Tracks') {
      try {
        // Set up callback for when user selects a backing track file
        window.JK = window.JK || {};
        window.JK.HandleBackingTrackSelectedCallback = (result) => {
          console.log('Backing track selected:', result);
          // Only proceed if a file was actually selected (user didn't cancel)
          if (result && result.file && onBackingTrackSelected) {
            onBackingTrackSelected(result);
          }
        };

        // Show the file selection dialog
        await jamClient.ShowSelectBackingTrackDialog("window.JK.HandleBackingTrackSelectedCallback");
      } catch (error) {
        console.error('Error opening backing track dialog:', error);
      }
    } else if (item === 'Metronome') {
      try {
        if (onMetronomeSelected) {
          onMetronomeSelected();
        }
      } catch (error) {
        console.error('Error opening metronome:', error);
      }
    }
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        buttonRef.current &&
        !buttonRef.current.contains(event.target) &&
        menuRef.current &&
        !menuRef.current.contains(event.target)
      ) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  // Close on escape key
  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown);
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen]);

  const buttonRect = buttonRef.current?.getBoundingClientRect();
  const menuStyle = buttonRect ? {
    position: 'absolute',
    top: buttonRect.bottom + window.scrollY,
    left: buttonRect.left + window.scrollX,
    zIndex: 999999,
    minWidth: '160px',
  } : {};

  return (
    <>
      <button
        ref={buttonRef}
        className='btn btn-outline-secondary btn-md'
        onClick={toggle}
        type="button"
      >
        <img src={openIcon} alt="Open" style={{ width: '20px', height: '20px', marginRight: '0.3rem' }} />
        Open
      </button>

      {isOpen && createPortal(
        <div
          ref={menuRef}
          style={menuStyle}
          className="dropdown-menu show"
        >
          <button
            className={`dropdown-item ${isAnyMediaOpen ? 'disabled' : ''}`}
            onClick={() => handleMenuItemClick('JamTracks')}
            disabled={isAnyMediaOpen}
            style={isAnyMediaOpen ? { opacity: 0.5, cursor: 'not-allowed' } : {}}
          >
            JamTrack...
          </button>
          <button
            className={`dropdown-item ${isAnyMediaOpen ? 'disabled' : ''}`}
            onClick={() => handleMenuItemClick('Backing Tracks')}
            disabled={isAnyMediaOpen}
            style={isAnyMediaOpen ? { opacity: 0.5, cursor: 'not-allowed' } : {}}
          >
            Backing Track...
          </button>
          <button
            className={`dropdown-item ${isAnyMediaOpen ? 'disabled' : ''}`}
            onClick={() => handleMenuItemClick('Metronome')}
            disabled={isAnyMediaOpen}
            style={isAnyMediaOpen ? { opacity: 0.5, cursor: 'not-allowed' } : {}}
          >
            Metronome...
          </button>
        </div>,
        document.body
      )}
    </>
  );
};

export default JKSessionOpenMenu;
