import { useEffect, useRef } from 'react';
import { Play, Pause, Volume2, Music2, SkipBack, SkipForward, Loader2 } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
import { useMusic } from '@/contexts/MusicContext';
import { motion, AnimatePresence } from 'framer-motion';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useState } from 'react';

const MusicPlayer = () => {
  const [isExpanded, setIsExpanded] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const { playSound, soundEnabled } = useSettings();
  const {
    isPlaying,
    isBuffering,
    volume,
    stations,
    currentIndex,
    selectedStation,
    setVolume,
    togglePlay,
    playNext,
    playPrevious,
    fetchStations,
  } = useMusic();

  useEffect(() => {
    if (isExpanded) {
      fetchStations();
    }
  }, [isExpanded, fetchStations]);

  // Close on click outside (for mobile)
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent | TouchEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsExpanded(false);
      }
    };

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

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

  const handleButtonClick = (action: () => void) => {
    if (soundEnabled) {
      playSound('click');
    }
    action();
  };

  const handleToggleExpand = () => {
    setIsExpanded(!isExpanded);
  };

  return (
    <div 
      ref={containerRef}
      className="fixed bottom-4 left-4 z-50"
      onMouseEnter={() => setIsExpanded(true)}
      onMouseLeave={() => setIsExpanded(false)}
    >
      <AnimatePresence>
        {isExpanded ? (
          <motion.div
            initial={{ opacity: 0, scale: 0.8, x: -20 }}
            animate={{ opacity: 1, scale: 1, x: 0 }}
            exit={{ opacity: 0, scale: 0.8, x: -20 }}
            transition={{ duration: 0.2 }}
            className="bg-background/95 border border-primary box-glow p-3 w-64"
          >
            {/* Header */}
            <div className="flex items-center gap-2 mb-3">
              <Music2 className="w-4 h-4 text-primary" />
              <span className="font-minecraft text-sm text-primary text-glow">Radio</span>
              {isBuffering && (
                <Loader2 className="w-3 h-3 text-primary animate-spin ml-auto" />
              )}
            </div>

            {/* Now Playing with Tooltip */}
            <Tooltip>
              <TooltipTrigger asChild>
                <div className="mb-3 p-2 bg-primary/10 border border-primary/30 cursor-help">
                  <p className="font-pixel text-xs text-primary truncate">
                    {selectedStation?.name || 'No station selected'}
                  </p>
                  <p className="font-pixel text-[10px] text-foreground/60 truncate">
                    {selectedStation?.country || 'Press play to start'}
                  </p>
                  {isPlaying && selectedStation && !isBuffering && (
                    <div className="flex gap-0.5 mt-1">
                      <span className="w-0.5 h-2 bg-primary animate-pulse" style={{ animationDelay: '0ms' }} />
                      <span className="w-0.5 h-2 bg-primary animate-pulse" style={{ animationDelay: '150ms' }} />
                      <span className="w-0.5 h-2 bg-primary animate-pulse" style={{ animationDelay: '300ms' }} />
                    </div>
                  )}
                  {isBuffering && (
                    <p className="font-pixel text-[10px] text-primary/60 mt-1">Buffering...</p>
                  )}
                </div>
              </TooltipTrigger>
              {selectedStation && (
                <TooltipContent side="top" className="bg-background border border-primary p-2 max-w-[200px]">
                  <div className="font-pixel text-xs space-y-1">
                    <p className="text-primary font-bold">{selectedStation.name}</p>
                    <p className="text-foreground/70">Country: {selectedStation.country || 'Unknown'}</p>
                    {selectedStation.bitrate > 0 && (
                      <p className="text-foreground/70">Bitrate: {selectedStation.bitrate}kbps</p>
                    )}
                    {selectedStation.tags && (
                      <p className="text-foreground/70 truncate">Tags: {selectedStation.tags.split(',').slice(0, 3).join(', ')}</p>
                    )}
                  </div>
                </TooltipContent>
              )}
            </Tooltip>

            {/* Playback Controls */}
            <div className="flex items-center justify-center gap-2 mb-3">
              <button
                onClick={() => handleButtonClick(playPrevious)}
                className="p-2 border border-primary/50 text-primary hover:bg-primary hover:text-background transition-all duration-300"
                aria-label="Previous station"
              >
                <SkipBack size={14} />
              </button>
              <button
                onClick={() => handleButtonClick(togglePlay)}
                className="p-2.5 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300"
                disabled={isBuffering}
                aria-label={isBuffering ? 'Loading' : isPlaying ? 'Pause' : 'Play'}
              >
                {isBuffering ? (
                  <Loader2 size={16} className="animate-spin" />
                ) : isPlaying ? (
                  <Pause size={16} />
                ) : (
                  <Play size={16} />
                )}
              </button>
              <button
                onClick={() => handleButtonClick(playNext)}
                className="p-2 border border-primary/50 text-primary hover:bg-primary hover:text-background transition-all duration-300"
                aria-label="Next station"
              >
                <SkipForward size={14} />
              </button>
            </div>

            {/* Volume */}
            <div className="flex items-center gap-2">
              <Volume2 size={12} className="text-primary" />
              <input
                type="range"
                min="0"
                max="100"
                value={volume}
                onChange={(e) => setVolume(Number(e.target.value))}
                aria-label="Volume control"
                className="flex-1 h-1 bg-primary/30 appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-2 [&::-webkit-slider-thumb]:h-2 [&::-webkit-slider-thumb]:bg-primary"
              />
              <span className="font-pixel text-[10px] text-primary w-8">{volume}%</span>
            </div>

            {/* Station count */}
            <p className="font-pixel text-[9px] text-foreground/40 text-center mt-2">
              {stations.length > 0 ? `${currentIndex + 1}/${stations.length} stations` : 'Loading...'}
            </p>
          </motion.div>
        ) : (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="p-3 bg-background/90 border border-primary box-glow cursor-pointer"
            onClick={handleToggleExpand}
            onTouchEnd={(e) => {
              e.preventDefault();
              handleToggleExpand();
            }}
          >
            <Music2 className="w-5 h-5 text-primary text-glow" />
            {isPlaying && (
              <div className="absolute -top-1 -right-1 w-2 h-2 bg-primary rounded-full animate-pulse" />
            )}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default MusicPlayer;
