import React, { useEffect, useState, useCallback } from 'react';
import { useSelector } from 'react-redux';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter, FormGroup, Label, Input, Table, Row, Col } from 'reactstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlay, faPause, faStop, faVolumeUp, faDownload, faEdit, faTrash, faPlus, faMinus, faQuestionCircle } from '@fortawesome/free-solid-svg-icons';
import { useAuth } from '../../context/UserAuth';
import { useJamClient } from '../../context/JamClientContext';
import { toast } from 'react-toastify';
import useMediaActions from '../../hooks/useMediaActions';
import { selectMediaSummary, selectMetronome } from '../../store/features/mixersSlice';
import {
  selectBackingTracks,
  selectJamTracks,
  selectRecordedTracks,
  selectJamTrackState,
  selectDownloadState
} from '../../store/features/mediaSlice';
import {
  selectShowMyMixes,
  selectShowCustomMixes,
  selectEditingMixdownId,
  selectCreatingMixdown,
  selectCreateMixdownErrors
} from '../../store/features/sessionUISlice';

const JKPopupMediaControls = ({ onClose }) => {
  const { currentUser } = useAuth();
  const { jamClient } = useJamClient();

  // Redux state
  const mediaSummary = useSelector(selectMediaSummary);
  const backingTracks = useSelector(selectBackingTracks);
  const jamTracks = useSelector(selectJamTracks);
  const recordedTracks = useSelector(selectRecordedTracks);
  const metronome = useSelector(selectMetronome);
  const jamTrackState = useSelector(selectJamTrackState);
  const downloadState = useSelector(selectDownloadState);
  const showMyMixes = useSelector(selectShowMyMixes);
  const showCustomMixes = useSelector(selectShowCustomMixes);
  const editingMixdownId = useSelector(selectEditingMixdownId);
  const creatingMixdown = useSelector(selectCreatingMixdown);
  const createMixdownErrors = useSelector(selectCreateMixdownErrors);

  // Compute if JamTrack is currently downloading
  const downloadingJamTrack = downloadState.state === 'downloading' || downloadState.state === 'checking' || downloadState.state === 'keying';

  // Redux actions
  const {
    closeMedia,
    toggleMyMixes,
    toggleCustomMixes,
    editMixdown,
    setMixdownErrors
  } = useMediaActions();

  const [time, setTime] = useState('0:00');
  const [isPlaying, setIsPlaying] = useState(false);
  const [loopEnabled, setLoopEnabled] = useState(false);

  // Get file name helper
  const getFileName = (file) => {
    if (!file) return 'Unknown File';
    if (file.path) {
      return file.path.split('/').pop().split('\\').pop();
    }
    if (file.name) {
      return file.name;
    }
    return 'Audio File';
  };

  // Handle close
  const handleClose = async () => {
    try {
      if (!mediaSummary.isOpener && !mediaSummary.metronomeOpen) {
        console.log("Only opener can close media");
        return;
      }
      await closeMedia();
      if (onClose) onClose();
    } catch (error) {
      console.error('Error closing media:', error);
    }
  };

  // Handle metronome display
  const handleShowMetronome = async () => {
    try {
      await jamClient.SessionShowNativeMetronomeGui();
    } catch (error) {
      console.error('Error showing metronome:', error);
    }
  };

  // JamTrack actions
  const handleJamTrackPlay = async (jamTrack) => {
    try {
      await jamClient.JamTrackActivateNoMixdown(jamTrack);
    } catch (error) {
      console.error('Error playing jam track:', error);
    }
  };

  const handleMixdownPlay = async (mixdown) => {
    try {
      editMixdown(null);
      await jamClient.JamTrackActivateMixdown(mixdown);
    } catch (error) {
      console.error('Error playing mixdown:', error);
    }
  };

  const handleMixdownEdit = (mixdown) => {
    editMixdown(mixdown.id);
  };

  const handleMixdownSave = async (mixdown) => {
    // Implementation for saving mixdown name
    editMixdown(null);
  };

  const handleMixdownDelete = async (mixdown) => {
    if (window.confirm("Delete this custom mix?")) {
      try {
        await jamClient.JamTrackDeleteMixdown(mixdown);
      } catch (error) {
        console.error('Error deleting mixdown:', error);
      }
    }
  };

  const handleDownloadMixdown = async (mixdown) => {
    // Implementation for downloading mixdown
    console.log('Download mixdown:', mixdown);
  };

  const handleCreateMix = async () => {
    // Implementation for creating custom mix
    console.log('Create custom mix');
  };

  // Determine content based on media type
  const renderContent = () => {
    // Backing Track
    if (mediaSummary.backingTrackOpen && backingTracks.length > 0) {
      const backingTrack = backingTracks[0];
      return (
        <div className="media-controls-popup">
          <div className="header">
            <h3>Audio File: {getFileName(backingTrack)}</h3>
          </div>

          <div className="field">
            <input
              type="checkbox"
              id="loop"
              checked={loopEnabled}
              onChange={(e) => setLoopEnabled(e.target.checked)}
            />
            <label htmlFor="loop">Loop audio file playback</label>
          </div>

          <div className="actions">
            <Button color="secondary" onClick={handleClose}>
              Close Audio File
            </Button>
          </div>
        </div>
      );
    }

    // JamTrack
    if (mediaSummary.jamTrackOpen && jamTrackState.jamTrack) {
      const jamTrack = jamTrackState.jamTrack;
      const selectedMixdown = jamTrack.activeMixdown;

      return (
        <div className="media-controls-popup">
          <div className="header">
            <h3>JamTrack: {jamTrack.name}</h3>
            <h4>
              {selectedMixdown ? 'Custom Mix' : 'Full JamTrack'}
              {downloadingJamTrack && ' (Loading...)'}
            </h4>
            {selectedMixdown && <h5>{selectedMixdown.name}</h5>}
          </div>

          {/* My Mixes Section */}
          <div className="my-mixes-section">
            <h4 onClick={toggleMyMixes} style={{ cursor: 'pointer' }}>
              My Mixes {showMyMixes ? '▼' : '▶'}
            </h4>
            {showMyMixes && (
              <div className="my-mixes">
                {/* Full Track Option */}
                <div className={`mixdown-display ${!selectedMixdown ? 'active' : ''}`}>
                  <div className="mixdown-name">Full JamTrack</div>
                  <div className="mixdown-actions">
                    <Button size="sm" onClick={() => handleJamTrackPlay(jamTrack)}>
                      <FontAwesomeIcon icon={faPlay} />
                    </Button>
                  </div>
                </div>

                {/* Custom Mixes */}
                {jamTrack.mixdowns && jamTrack.mixdowns.map(mixdown => (
                  <div key={mixdown.id} className={`mixdown-display ${selectedMixdown?.id === mixdown.id ? 'active' : ''}`}>
                    <div className="mixdown-name">
                      {editingMixdownId === mixdown.id ? (
                        <Input
                          type="text"
                          defaultValue={mixdown.name}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter') handleMixdownSave(mixdown);
                            if (e.key === 'Escape') editMixdown(null);
                          }}
                        />
                      ) : (
                        mixdown.name
                      )}
                    </div>
                    <div className="mixdown-actions">
                      <Button size="sm" onClick={() => handleMixdownPlay(mixdown)}>
                        <FontAwesomeIcon icon={faPlay} />
                      </Button>
                      <Button size="sm" onClick={() => handleDownloadMixdown(mixdown)}>
                        <FontAwesomeIcon icon={faDownload} />
                      </Button>
                      <Button size="sm" onClick={() => handleMixdownEdit(mixdown)}>
                        <FontAwesomeIcon icon={faEdit} />
                      </Button>
                      <Button size="sm" color="danger" onClick={() => handleMixdownDelete(mixdown)}>
                        <FontAwesomeIcon icon={faTrash} />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Create Custom Mix Section */}
          <div className="custom-mix-section">
            <h4 onClick={toggleCustomMixes} style={{ cursor: 'pointer' }}>
              Create Custom Mix {showCustomMixes ? '▼' : '▶'}
            </h4>
            {showCustomMixes && (
              <div className="create-mix">
                <p>Use the JamTrack controls on the session screen to set levels, mute/unmute, or pan any of the parts of the JamTrack as you like.</p>

                <FormGroup>
                  <Label>Change Tempo:</Label>
                  <Input type="select" name="mix-speed">
                    <option value="">No change</option>
                    <option value="-5">Slower by 5%</option>
                    <option value="-10">Slower by 10%</option>
                    <option value="5">Faster by 5%</option>
                    <option value="10">Faster by 10%</option>
                  </Input>
                </FormGroup>

                <FormGroup>
                  <Label>Change Pitch:</Label>
                  <Input type="select" name="mix-pitch">
                    <option value="">No change</option>
                    <option value="-1">Down 1 Semitone</option>
                    <option value="1">Up 1 Semitone</option>
                  </Input>
                </FormGroup>

                <FormGroup>
                  <Label>Mix Name:</Label>
                  <Input type="text" name="mix-name" />
                </FormGroup>

                <Button
                  color="primary"
                  onClick={handleCreateMix}
                  disabled={creatingMixdown}
                >
                  {creatingMixdown ? 'Creating...' : 'CREATE MIX'}
                </Button>
              </div>
            )}
          </div>

          <div className="actions">
            <Button color="link" href="https://jamkazam.desk.com/customer/portal/articles/2138903-using-custom-mixes-to-slow-tempo-change-pitch" target="_blank">
              <FontAwesomeIcon icon={faQuestionCircle} /> HELP
            </Button>
            <Button color="secondary" onClick={handleClose}>
              Close JamTrack
            </Button>
          </div>
        </div>
      );
    }

    // Metronome
    if (mediaSummary.metronomeOpen) {
      return (
        <div className="media-controls-popup">
          <div className="header">
            <h3>Metronome</h3>
          </div>

          <div className="field">
            <Button color="secondary" onClick={handleShowMetronome}>
              Display visual metronome
            </Button>
          </div>

          <div className="actions">
            <Button color="secondary" onClick={handleClose}>
              Close Metronome
            </Button>
          </div>
        </div>
      );
    }

    // Recording
    if (mediaSummary.recordingOpen) {
      return (
        <div className="media-controls-popup">
          <div className="header">
            <h3>Recording</h3>
          </div>

          <div className="actions">
            <Button color="secondary" onClick={handleClose}>
              Close Recording
            </Button>
          </div>
        </div>
      );
    }

    return (
      <div className="media-controls-popup">
        <div className="header">
          <h3>Media Controls</h3>
        </div>
        <p>No media currently open</p>
        <div className="actions">
          <Button color="secondary" onClick={onClose}>
            Close
          </Button>
        </div>
      </div>
    );
  };

  return (
    <div style={{
      width: '100vw',
      height: '100vh',
      display: 'flex',
      flexDirection: 'column',
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", sans-serif',
      backgroundColor: '#f8f9fa',
      padding: '20px',
      overflow: 'auto'
    }}>
      {renderContent()}
    </div>
  );
};

export default JKPopupMediaControls;
