/**
 * VEZA V5 ULTRA - ENHANCED AUDIO PLAYER
 * Player professionnel avec Audio Engine V5, Equalizer, et Visualizer 3D
 */

import { useState, useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import {
  Play,
  Pause,
  SkipBack,
  SkipForward,
  Volume2,
  VolumeX,
  Repeat,
  Shuffle,
  Heart,
  MoreHorizontal,
  Maximize2,
} from 'lucide-react';
import { getAudioEngine, type Track, type AudioAnalysis } from '@/services/audio-engine-v5';
import { AudioVisualizer3D, MiniVisualizer } from '@/components/audio/AudioVisualizer3D';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import { cn } from '@/lib/utils';

interface EnhancedAudioPlayerProps {
  currentTrack?: Track | null;
  queue?: Track[];
  onNext?: () => void;
  onPrevious?: () => void;
  onTrackEnd?: () => void;
  showVisualizer?: boolean;
  showEqualizer?: boolean;
  className?: string;
}

export function EnhancedAudioPlayer({
  currentTrack,
  queue = [],
  onNext,
  onPrevious,
  onTrackEnd,
  showVisualizer = true,
  showEqualizer = false,
  className = '',
}: EnhancedAudioPlayerProps) {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(80);
  const [isMuted, setIsMuted] = useState(false);
  const [analysis, setAnalysis] = useState<AudioAnalysis | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isLiked, setIsLiked] = useState(false);
  const [visualizerMode, setVisualizerMode] = useState<'bars' | 'particles' | 'hybrid'>('hybrid');

  const engine = getAudioEngine();

  // Load track when currentTrack changes
  useEffect(() => {
    if (!currentTrack) return;

    const loadTrack = async () => {
      try {
        setIsLoading(true);
        await engine.loadTrack(currentTrack);
        setDuration(currentTrack.duration);
        setIsLoading(false);
        
        // Auto-play si déjà en train de jouer
        if (isPlaying) {
          await engine.play();
        }
      } catch (error) {
        console.error('Failed to load track:', error);
        setIsLoading(false);
      }
    };

    loadTrack();
  }, [currentTrack?.id]);

  // Setup callbacks
  useEffect(() => {
    engine.onTimeUpdateCallback(setCurrentTime);
    engine.onTrackEndCallback(() => {
      setIsPlaying(false);
      onTrackEnd?.();
    });
    engine.onAnalysisUpdateCallback(setAnalysis);

    return () => {
      // Cleanup callbacks
      engine.onTimeUpdateCallback(() => {});
      engine.onTrackEndCallback(() => {});
      engine.onAnalysisUpdateCallback(() => {});
    };
  }, [onTrackEnd]);

  // Handle play/pause
  const handlePlayPause = useCallback(async () => {
    if (!currentTrack) return;

    try {
      if (isPlaying) {
        engine.pause();
        setIsPlaying(false);
      } else {
        await engine.play();
        setIsPlaying(true);
      }
    } catch (error) {
      console.error('Playback error:', error);
    }
  }, [currentTrack, isPlaying]);

  // Handle seek
  const handleSeek = useCallback((value: number[]) => {
    const newTime = value[0];
    engine.seek(newTime);
    setCurrentTime(newTime);
  }, []);

  // Handle volume
  const handleVolumeChange = useCallback((value: number[]) => {
    const newVolume = value[0];
    setVolume(newVolume);
    engine.setVolume(newVolume / 100);
    if (newVolume > 0 && isMuted) {
      setIsMuted(false);
    }
  }, [isMuted]);

  // Toggle mute
  const handleMuteToggle = useCallback(() => {
    if (isMuted) {
      engine.setVolume(volume / 100);
      setIsMuted(false);
    } else {
      engine.setVolume(0);
      setIsMuted(true);
    }
  }, [isMuted, volume]);

  // Format time
  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyPress = (e: KeyboardEvent) => {
      // Ignore if typing in input
      if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
        return;
      }

      switch (e.key.toLowerCase()) {
        case ' ':
          e.preventDefault();
          handlePlayPause();
          break;
        case 'arrowleft':
          e.preventDefault();
          engine.seek(Math.max(0, currentTime - 10));
          break;
        case 'arrowright':
          e.preventDefault();
          engine.seek(Math.min(duration, currentTime + 10));
          break;
        case 'm':
          e.preventDefault();
          handleMuteToggle();
          break;
        case 'l':
          e.preventDefault();
          setIsLiked(prev => !prev);
          break;
      }
    };

    window.addEventListener('keydown', handleKeyPress);
    return () => window.removeEventListener('keydown', handleKeyPress);
  }, [currentTime, duration, handlePlayPause, handleMuteToggle]);

  if (!currentTrack) {
    return (
      <Card variant="glass" className={cn('p-8 text-center', className)}>
        <p className="text-muted-foreground">No track selected</p>
        <p className="text-sm text-muted-foreground mt-2">
          Select a track from your library to start playing
        </p>
      </Card>
    );
  }

  return (
    <Card variant="glass" className={cn('overflow-hidden', className)}>
      {/* Visualizer (optionnel, toggleable) */}
      {showVisualizer && (
        <div className="relative h-64 bg-gradient-to-b from-black/20 to-transparent">
          <AudioVisualizer3D
            analysis={analysis}
            mode={visualizerMode}
            className="h-full w-full"
          />
          
          {/* Visualizer Mode Switcher */}
          <div className="absolute top-4 right-4 flex gap-2">
            <Button
              variant={visualizerMode === 'bars' ? 'gradient' : 'glass'}
              size="sm"
              onClick={() => setVisualizerMode('bars')}
            >
              Bars
            </Button>
            <Button
              variant={visualizerMode === 'particles' ? 'gradient' : 'glass'}
              size="sm"
              onClick={() => setVisualizerMode('particles')}
            >
              Particles
            </Button>
            <Button
              variant={visualizerMode === 'hybrid' ? 'gradient' : 'glass'}
              size="sm"
              onClick={() => setVisualizerMode('hybrid')}
            >
              Hybrid
            </Button>
          </div>
        </div>
      )}

      <div className="p-6 space-y-6">
        {/* Track Info */}
        <div className="flex items-center gap-4">
          {/* Artwork */}
          <div className="relative w-20 h-20 rounded-xl overflow-hidden flex-shrink-0 hover-lift">
            {currentTrack.artwork ? (
              <img
                src={currentTrack.artwork}
                alt={currentTrack.title}
                className="w-full h-full object-cover"
              />
            ) : (
              <div className="w-full h-full gradient-mesh" />
            )}
          </div>

          {/* Info */}
          <div className="flex-1 min-w-0">
            <h3 className="font-bold text-lg truncate">
              {currentTrack.title}
            </h3>
            <p className="text-sm text-muted-foreground truncate">
              {currentTrack.artist}
            </p>
          </div>

          {/* Actions */}
          <div className="flex gap-2">
            <Button
              variant={isLiked ? 'success' : 'ghost'}
              size="icon"
              onClick={() => setIsLiked(!isLiked)}
            >
              <Heart className={cn('w-5 h-5', isLiked && 'fill-current')} />
            </Button>
            <Button variant="ghost" size="icon">
              <MoreHorizontal className="w-5 h-5" />
            </Button>
          </div>
        </div>

        {/* Mini Visualizer (si 3D caché) */}
        {!showVisualizer && analysis && (
          <div className="h-16 rounded-lg overflow-hidden">
            <MiniVisualizer analysis={analysis} barCount={64} />
          </div>
        )}

        {/* Progress Bar */}
        <div className="space-y-2">
          <Slider
            value={[currentTime]}
            max={duration}
            step={0.1}
            onValueChange={handleSeek}
            className="cursor-pointer"
          />
          <div className="flex justify-between text-xs text-muted-foreground">
            <span>{formatTime(currentTime)}</span>
            <span>{formatTime(duration)}</span>
          </div>
        </div>

        {/* Controls */}
        <div className="flex items-center justify-center gap-4">
          <Button variant="ghost" size="icon">
            <Shuffle className="w-5 h-5" />
          </Button>

          <Button
            variant="ghost"
            size="icon"
            onClick={onPrevious}
            disabled={!onPrevious}
          >
            <SkipBack className="w-5 h-5" />
          </Button>

          <Button
            variant="gradient"
            size="icon"
            className="w-14 h-14"
            onClick={handlePlayPause}
            disabled={isLoading}
            loading={isLoading}
          >
            {isPlaying ? (
              <Pause className="w-6 h-6 fill-current" />
            ) : (
              <Play className="w-6 h-6 fill-current ml-1" />
            )}
          </Button>

          <Button
            variant="ghost"
            size="icon"
            onClick={onNext}
            disabled={!onNext}
          >
            <SkipForward className="w-5 h-5" />
          </Button>

          <Button variant="ghost" size="icon">
            <Repeat className="w-5 h-5" />
          </Button>
        </div>

        {/* Volume Control */}
        <div className="flex items-center gap-4">
          <Button
            variant="ghost"
            size="icon"
            onClick={handleMuteToggle}
          >
            {isMuted || volume === 0 ? (
              <VolumeX className="w-5 h-5" />
            ) : (
              <Volume2 className="w-5 h-5" />
            )}
          </Button>

          <Slider
            value={[volume]}
            max={100}
            step={1}
            onValueChange={handleVolumeChange}
            className="flex-1"
          />

          <span className="text-sm text-muted-foreground w-12 text-right">
            {volume}%
          </span>
        </div>

        {/* Queue Info */}
        {queue.length > 0 && (
          <div className="text-center text-sm text-muted-foreground">
            {queue.length} {queue.length === 1 ? 'track' : 'tracks'} in queue
          </div>
        )}

        {/* Keyboard Shortcuts Hint */}
        <div className="text-xs text-muted-foreground text-center space-x-3">
          <span><kbd className="px-1 py-0.5 bg-white/5 rounded">Space</kbd> Play/Pause</span>
          <span><kbd className="px-1 py-0.5 bg-white/5 rounded">←/→</kbd> Seek</span>
          <span><kbd className="px-1 py-0.5 bg-white/5 rounded">M</kbd> Mute</span>
          <span><kbd className="px-1 py-0.5 bg-white/5 rounded">L</kbd> Like</span>
        </div>
      </div>
    </Card>
  );
}

