'use client';

import { useState, useEffect, useRef } from 'react';
import { Howl } from 'howler';

interface Sound {
  id: number;
  name: string;
  file: string;
  category: string;
}

interface ActiveSound {
  id: number;
  volume: number;
  howl?: Howl;
  playing: boolean;
}

export default function Mixer() {
  const [sounds, setSounds] = useState<Sound[]>([]);
  const [activeSounds, setActiveSounds] = useState<ActiveSound[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [masterPlaying, setMasterPlaying] = useState(false);
  
  const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:5000';
  
  // Fetch sounds from the API
  useEffect(() => {
    const fetchSounds = async () => {
      try {
        // In a real app, fetch from API
        // const response = await fetch(`${backendUrl}/api/sounds`);
        // const data = await response.json();
        
        // For MVP, use hardcoded data
        const data = [
          { id: 1, name: 'Rain', file: '/sounds/rain.mp3', category: 'Nature' },
          { id: 2, name: 'Thunder', file: '/sounds/thunder.mp3', category: 'Nature' },
          { id: 3, name: 'Forest', file: '/sounds/forest.mp3', category: 'Nature' },
          { id: 4, name: 'Ocean Waves', file: '/sounds/ocean.mp3', category: 'Water' },
          { id: 5, name: 'Fireplace', file: '/sounds/fire.mp3', category: 'Ambience' },
          { id: 6, name: 'White Noise', file: '/sounds/white-noise.mp3', category: 'Noise' },
          { id: 7, name: 'Coffee Shop', file: '/sounds/coffee-shop.mp3', category: 'Ambience' },
          { id: 8, name: 'Birds', file: '/sounds/birds.mp3', category: 'Nature' }
        ];
        
        setSounds(data);
        setIsLoading(false);
      } catch (error) {
        console.error('Error fetching sounds:', error);
        setIsLoading(false);
      }
    };
    
    fetchSounds();
  }, [backendUrl]);
  
  // Handle adding a sound to the active mix
  const addSound = (sound: Sound) => {
    // Check if sound is already in the mix
    if (activeSounds.some(as => as.id === sound.id)) {
      return;
    }
    
    // Create a new Howl instance for the sound
    const howl = new Howl({
      src: [sound.file],
      loop: true,
      volume: 0.5,
      html5: true,
    });
    
    setActiveSounds(prev => [
      ...prev,
      {
        id: sound.id,
        volume: 0.5,
        howl,
        playing: false
      }
    ]);
  };
  
  // Handle removing a sound from the active mix
  const removeSound = (id: number) => {
    setActiveSounds(prev => {
      const updatedSounds = prev.filter(sound => sound.id !== id);
      const soundToRemove = prev.find(sound => sound.id === id);
      
      // Stop the sound if it's playing
      if (soundToRemove?.howl && soundToRemove.playing) {
        soundToRemove.howl.stop();
      }
      
      return updatedSounds;
    });
  };
  
  // Handle volume change for a specific sound
  const handleVolumeChange = (id: number, volume: number) => {
    setActiveSounds(prev => 
      prev.map(sound => {
        if (sound.id === id) {
          if (sound.howl) {
            sound.howl.volume(volume);
          }
          return { ...sound, volume };
        }
        return sound;
      })
    );
  };
  
  // Play or pause all active sounds
  const toggleMasterPlayback = () => {
    const newPlayingState = !masterPlaying;
    setMasterPlaying(newPlayingState);
    
    setActiveSounds(prev => 
      prev.map(sound => {
        if (sound.howl) {
          if (newPlayingState) {
            sound.howl.play();
          } else {
            sound.howl.pause();
          }
        }
        return { ...sound, playing: newPlayingState };
      })
    );
  };
  
  // Group sounds by category
  const soundsByCategory = sounds.reduce((acc, sound) => {
    if (!acc[sound.category]) {
      acc[sound.category] = [];
    }
    acc[sound.category].push(sound);
    return acc;
  }, {} as Record<string, Sound[]>);
  
  // Cleanup on unmount
  useEffect(() => {
    return () => {
      activeSounds.forEach(sound => {
        if (sound.howl) {
          sound.howl.stop();
        }
      });
    };
  }, [activeSounds]);
  
  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-emerald-500"></div>
      </div>
    );
  }
  
  return (
    <div className="mx-auto max-w-6xl">
      <h1 className="text-3xl font-bold mb-8 text-center text-emerald-600 dark:text-emerald-400">
        Sound Mixer
      </h1>
      
      <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
        {/* Sound Library */}
        <div className="md:col-span-1 bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
          <h2 className="text-xl font-semibold mb-4 text-emerald-600 dark:text-emerald-400">
            Sound Library
          </h2>
          
          {Object.entries(soundsByCategory).map(([category, categorySounds]) => (
            <div key={category} className="mb-6">
              <h3 className="text-lg font-medium mb-2 text-gray-700 dark:text-gray-300">
                {category}
              </h3>
              <div className="space-y-2">
                {categorySounds.map(sound => (
                  <div 
                    key={sound.id}
                    className="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-600 cursor-pointer transition"
                    onClick={() => addSound(sound)}
                  >
                    <span>{sound.name}</span>
                    <button 
                      className="text-xs px-2 py-1 bg-emerald-100 dark:bg-emerald-900 text-emerald-600 dark:text-emerald-400 rounded"
                      onClick={(e) => {
                        e.stopPropagation();
                        addSound(sound);
                      }}
                    >
                      Add
                    </button>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
        
        {/* Sound Mixer */}
        <div className="md:col-span-2 bg-white dark:bg-gray-800 p-6 rounded-lg shadow-md">
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-xl font-semibold text-emerald-600 dark:text-emerald-400">
              Your Mix
            </h2>
            <button
              className={`px-4 py-2 rounded-lg shadow-md transition ${
                masterPlaying
                  ? 'bg-red-500 hover:bg-red-600 text-white'
                  : 'bg-emerald-500 hover:bg-emerald-600 text-white'
              }`}
              onClick={toggleMasterPlayback}
            >
              {masterPlaying ? 'Pause All' : 'Play All'}
            </button>
          </div>
          
          {activeSounds.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <p>Add sounds from the library to start mixing</p>
            </div>
          ) : (
            <div className="space-y-4">
              {activeSounds.map(sound => {
                const soundDetails = sounds.find(s => s.id === sound.id);
                return (
                  <div key={sound.id} className="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                    <div className="flex justify-between items-center mb-2">
                      <span className="font-medium">{soundDetails?.name}</span>
                      <button
                        className="text-red-500 hover:text-red-700 transition"
                        onClick={() => removeSound(sound.id)}
                      >
                        Remove
                      </button>
                    </div>
                    <div className="flex items-center gap-4">
                      <span className="text-xs w-8">0%</span>
                      <input
                        type="range"
                        min="0"
                        max="1"
                        step="0.01"
                        value={sound.volume}
                        onChange={(e) => handleVolumeChange(sound.id, parseFloat(e.target.value))}
                        className="w-full accent-emerald-500"
                      />
                      <span className="text-xs w-8">100%</span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
