import React, { useState, useEffect, useRef, useCallback } from 'react';

const MOOD_COLORS = {
  combat: 'bg-red-900 border-red-600 hover:bg-red-800',
  investigation: 'bg-blue-900 border-blue-600 hover:bg-blue-800',
  tension: 'bg-purple-900 border-purple-600 hover:bg-purple-800',
  victory: 'bg-amber-900 border-amber-600 hover:bg-amber-800',
  eerie: 'bg-green-900 border-green-600 hover:bg-green-800',
};

const MOOD_ICONS = {
  combat: '⚔️',
  investigation: '🔍',
  tension: '⚡',
  victory: '🏆',
  eerie: '👁️',
};

export default function MoodMusic() {
  const [manifest, setManifest] = useState([]);
  const [activeMood, setActiveMood] = useState(null);
  const [volume, setVolume] = useState(0.3);
  const [nowPlaying, setNowPlaying] = useState('');
  const [loading, setLoading] = useState(true);
  const audioRef = useRef(null);
  const fadeTimeoutRef = useRef(null);

  // Fetch manifest on mount
  useEffect(() => {
    fetch('/api/music/manifest')
      .then((r) => r.json())
      .then((data) => {
        setManifest(Array.isArray(data) ? data : []);
        setLoading(false);
      })
      .catch((err) => {
        console.error('Failed to load music manifest:', err);
        setManifest([]);
        setLoading(false);
      });
  }, []);

  // Create audio element on mount (volume handled by separate effect)
  useEffect(() => {
    const audio = new Audio();
    audio.preload = 'auto';
    audio.loop = true;
    audioRef.current = audio;
    return () => {
      if (fadeTimeoutRef.current) clearTimeout(fadeTimeoutRef.current);
      audio.pause();
      audio.src = '';
    };
  }, []);

  // Set initial volume on mount, then update whenever volume changes
  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.volume = volume;
    }
  }, [volume]);

  const stopPlayback = useCallback(() => {
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.src = '';
    }
    setActiveMood(null);
    setNowPlaying('');
  }, []);

  const playMood = useCallback((track) => {
    if (!track || !audioRef.current) return;

    const audio = audioRef.current;
    const url = `/music/${track.file}`;

    // If switching to same track, stop
    if (activeMood === track.mood && audio.src === url) {
      stopPlayback();
      return;
    }

    // Fade out current, then switch
    if (fadeTimeoutRef.current) clearTimeout(fadeTimeoutRef.current);

    // Quick fade out
    const fadeOut = () => {
      audio.volume = Math.max(0, audio.volume - 0.1);
      if (audio.volume > 0) {
        fadeTimeoutRef.current = setTimeout(fadeOut, 30);
      } else {
        // Switch source and fade in
        audio.src = url;
        audio.load();
        audio.play().catch((e) => console.warn('Audio play failed:', e));
        setActiveMood(track.mood);
        setNowPlaying(track.title);

        // Fade in
        const fadeIn = () => {
          audio.volume = Math.min(volume, audio.volume + 0.05);
          if (audio.volume < volume) {
            fadeTimeoutRef.current = setTimeout(fadeIn, 30);
          }
        };
        if (volume > 0) {
          fadeTimeoutRef.current = setTimeout(fadeIn, 30);
        }
      }
    };

    if (audio.src && audio.src !== url) {
      fadeOut();
    } else {
      audio.src = url;
      audio.load();
      audio.play().catch((e) => console.warn('Audio play failed:', e));
      setActiveMood(track.mood);
      setNowPlaying(track.title);
    }
  }, [activeMood, volume, stopPlayback]);

  if (loading) {
    return (
      <div className="bg-slate-800 rounded-xl p-4 border border-slate-600">
        <h3 className="text-lg font-semibold text-slate-100 mb-2">Scene Music</h3>
        <p className="text-slate-400 text-sm">Loading music tracks...</p>
      </div>
    );
  }

  if (manifest.length === 0) {
    return (
      <div className="bg-slate-800 rounded-xl p-4 border border-slate-600">
        <h3 className="text-lg font-semibold text-slate-100 mb-2">Scene Music</h3>
        <p className="text-slate-400 text-sm">No music tracks available.</p>
      </div>
    );
  }

  return (
    <div className="bg-slate-800 rounded-xl p-4 border border-slate-600">
      <h3 className="text-lg font-semibold text-slate-100 mb-3">Scene Music</h3>

      {/* Mood buttons */}
      <div className="grid grid-cols-5 gap-2 mb-4">
        {manifest.map((track) => {
          const isActive = activeMood === track.mood;
          const colorClass = MOOD_COLORS[track.mood] || 'bg-slate-700 border-slate-500 hover:bg-slate-600';
          return (
            <button
              key={track.mood}
              onClick={() => playMood(track)}
              className={`p-3 rounded-lg border-2 text-center transition-all ${colorClass} ${
                isActive ? 'ring-2 ring-white text-white font-bold scale-105' : 'text-slate-200'
              }`}
              title={track.title}
            >
              <div className="text-xl mb-1">{MOOD_ICONS[track.mood] || '🎵'}</div>
              <div className="text-xs uppercase tracking-wide">{track.mood}</div>
            </button>
          );
        })}
      </div>

      {/* Stop button */}
      {activeMood && (
        <button
          onClick={stopPlayback}
          className="w-full mb-4 px-4 py-2 bg-red-800 hover:bg-red-700 text-white rounded-lg border border-red-600 transition-colors text-sm font-medium"
        >
          ■ Stop Music
        </button>
      )}

      {/* Volume control */}
      <div className="mb-3">
        <label className="text-xs text-slate-400 mb-1 block">Volume</label>
        <input
          type="range"
          min="0"
          max="1"
          step="0.01"
          value={volume}
          onChange={(e) => setVolume(parseFloat(e.target.value))}
          className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
        />
        <div className="text-xs text-slate-500 mt-1 text-right">{Math.round(volume * 100)}%</div>
      </div>

      {/* Now playing */}
      {nowPlaying && (
        <div className="text-xs text-slate-300 bg-slate-900 rounded px-3 py-2">
          <span className="text-slate-500">Now playing:</span> {nowPlaying}
        </div>
      )}
    </div>
  );
}