import React, { useState, useRef } from 'react';
import { usePlayer } from '@/features/player/hooks/usePlayer';
import { useKeyboardShortcuts } from '@/features/player/hooks/useKeyboardShortcuts';
import { Slider } from '@/components/ui/slider';
import { cn } from '@/lib/utils';
import {
  Heart, Maximize2, ListMusic, Volume2, VolumeX
} from 'lucide-react';
import { PlayerControls } from './PlayerControls';
import { PlayerQueue } from './PlayerQueue';
import { PlayerExpanded } from './PlayerExpanded';
import { Button } from '@/components/ui/button';

// Enhanced Waveform Visualization
const Waveform = ({ playing }: { playing: boolean }) => {
  return (
    <div className="flex items-center gap-[3px] h-8 opacity-60">
      {Array.from({ length: 24 }).map((_, i) => (
        <div
          key={i}
          className={cn(
            "w-[3px] bg-gradient-to-t from-cyan-500 to-magenta-500 rounded-full transition-all duration-300",
            playing ? "animate-[eq-bounce_0.5s_ease-in-out_infinite]" : "h-1"
          )}
          style={{
            height: playing ? `${20 + Math.random() * 80}%` : '15%',
            animationDelay: `${Math.random() * 0.5}s`,
            animationDuration: `${0.4 + Math.random() * 0.4}s`
          }}
        />
      ))}
    </div>
  );
};

export function GlobalPlayer() {
  const audioRef = useRef<HTMLAudioElement>(null);

  // Use the REAL player hook logic which connects to Zustand store
  const player = usePlayer(audioRef);

  // Enable keyboard shortcuts
  useKeyboardShortcuts(player);

  const [isHovered, setIsHovered] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);
  const [showQueue, setShowQueue] = useState(false);

  const formatTime = (seconds: number) => {
    if (!seconds && seconds !== 0) return '0:00';
    const m = Math.floor(seconds / 60);
    const s = Math.floor(seconds % 60);
    return `${m}:${s.toString().padStart(2, '0')}`;
  };

  const currentTrack = player.currentTrack;

  // Placeholder track for idle state
  const idleTrack = {
    id: 'idle',
    title: 'System Online',
    artist: 'Select a track to play',
    cover: '',
    duration: 0,
    url: ''
  };

  const displayTrack = currentTrack || idleTrack;
  const isIdle = !currentTrack;

  return (
    <>
      <audio
        ref={audioRef}
        onEnded={() => {
          // Hook handles onEnded via audioService listeners
        }}
      />

      {/* Expanded View Modal - Guarded against null track */}
      <PlayerExpanded
        isOpen={isExpanded}
        onClose={() => setIsExpanded(false)}
        currentTime={player.currentTime}
        duration={player.duration}
        onSeek={player.seek}
        player={player}
      />

      {/* Queue Drawer */}
      <PlayerQueue
        isOpen={showQueue}
        onClose={() => setShowQueue(false)}
        currentTrackId={currentTrack?.id}
        onPlay={(track) => player.play(track)}
      />

      {/* Main Floating Player */}
      <div
        className={cn(
          "fixed bottom-6 left-4 right-4 md:left-1/2 md:-translate-x-1/2 md:w-full md:max-w-5xl z-[100] transition-all duration-500 ease-[cubic-bezier(0.32,0.72,0,1)]",
          isExpanded ? "translate-y-[200%] opacity-0" : "translate-y-0 opacity-100"
        )}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      >
        {/* Glass Container */}
        <div className={cn(
          "relative rounded-2xl overflow-hidden backdrop-blur-2xl transition-all duration-300 group shadow-2xl",
          "bg-black/80 border border-white/10", // Darker more premium base
          isHovered ? "shadow-[0_0_50px_rgba(var(--cyan-500),0.15)] border-primary/30" : "box-shadow-[0_8px_32px_rgba(0,0,0,0.5)]"
        )}>

          {/* Progress Bar (Top Edge) */}
          <div className={cn("absolute top-0 left-0 right-0 h-[2px] bg-white/5 z-20 transition-all", !isIdle && "group-hover:h-[4px] cursor-pointer")}
            onClick={(e) => {
              if (isIdle) return;
              const rect = e.currentTarget.getBoundingClientRect();
              const x = e.clientX - rect.left;
              const pct = x / rect.width;
              player.seek(pct * player.duration);
            }}>
            <div
              className={cn("h-full bg-gradient-to-r from-cyan-500 via-blue-500 to-magenta-500 relative", isIdle && "w-0 opacity-0")}
              style={{ width: !isIdle ? `${(player.currentTime / (player.duration || 1)) * 100}%` : '0%' }}
            >
              <div className="absolute right-0 top-1/2 -translate-y-1/2 w-3 h-3 bg-white rounded-full shadow-[0_0_10px_white] opacity-0 group-hover:opacity-100 transition-opacity scale-0 group-hover:scale-100" />
            </div>
          </div>

          <div className="flex items-center justify-between h-20 md:h-24 px-4 md:px-6 relative z-10">

            {/* LEFT: Track Info */}
            <div className="flex items-center gap-4 flex-1 min-w-0">
              <div
                className={cn("relative w-12 h-12 md:w-14 md:h-14 rounded-lg overflow-hidden group/art", !isIdle && "cursor-pointer")}
                onClick={() => !isIdle && setIsExpanded(true)}
              >
                {displayTrack.cover ? (
                  <img
                    src={displayTrack.cover}
                    alt={displayTrack.title}
                    className={cn("w-full h-full object-cover transition-transform duration-700", player.isPlaying && "scale-110")}
                  />
                ) : (
                  <div className="w-full h-full bg-white/5 flex items-center justify-center">
                    <Maximize2 className={cn("w-6 h-6 text-muted-foreground", isIdle && "opacity-20")} />
                  </div>
                )}

                {!isIdle && (
                  <div className="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover/art:opacity-100 transition-opacity">
                    <Maximize2 className="w-5 h-5 text-white" />
                  </div>
                )}
              </div>

              <div className="flex flex-col justify-center min-w-0">
                <div className="flex items-center gap-2">
                  <h3 className={cn("font-display font-bold text-sm md:text-base text-white truncate transition-colors", !isIdle && "hover:text-primary cursor-pointer")}
                    onClick={() => !isIdle && setIsExpanded(true)}>
                    {displayTrack.title}
                  </h3>
                  {/* Quality Badge - Show only if not idle */}
                  {!isIdle && (
                    <span className="hidden md:inline-flex px-1.5 py-0.5 rounded text-[9px] font-mono bg-white/5 text-muted-foreground border border-white/10 uppercase tracking-wider">
                      HQ
                    </span>
                  )}
                </div>
                <p className={cn("text-xs text-muted-foreground truncate transition-colors", !isIdle && "hover:text-white cursor-pointer")}
                  onClick={() => !isIdle && setIsExpanded(true)}>
                  {displayTrack.artist || 'Unknown Artist'}
                </p>
              </div>
            </div>

            {/* CENTER: Controls */}
            <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 flex flex-col items-center justify-center gap-1 min-w-[300px]">
              <PlayerControls
                isPlaying={player.isPlaying}
                onPlayPause={() => {
                  if (player.isPlaying) player.pause();
                  else if (!isIdle) player.resume();
                }}
                onNext={player.next}
                onPrevious={player.previous}
                onShuffle={player.toggleShuffle}
                onRepeat={() => {
                  const modes = ['off', 'track', 'playlist'] as const; // Should cycle
                  const next = modes[(modes.indexOf(player.repeat) + 1) % modes.length];
                  player.setRepeat(next);
                }}
                shuffle={player.shuffle}
                repeat={player.repeat}
              />
              <div className={cn("hidden md:flex items-center gap-2 text-[10px] font-mono text-muted-foreground w-full justify-center transition-opacity", !isIdle ? "opacity-0 group-hover:opacity-100" : "opacity-0")}>
                <span>{formatTime(player.currentTime)}</span>
                <span className="opacity-30">/</span>
                <span>{formatTime(player.duration)}</span>
              </div>
            </div>

            {/* RIGHT: Actions & Volume */}
            <div className="flex items-center justify-end gap-3 md:gap-4 flex-1">
              {/* Waveform Visualization (Desktop) */}
              <div className="hidden lg:block w-24 mr-2">
                <Waveform playing={player.isPlaying} />
              </div>

              {/* Volume */}
              <div className="hidden md:flex items-center gap-2 group/volume">
                <Button
                  variant="ghost"
                  size="icon"
                  className="w-8 h-8 text-muted-foreground hover:text-white"
                  onClick={player.toggleMute}
                >
                  {player.muted || player.volume === 0 ? <VolumeX className="w-4 h-4" /> : <Volume2 className="w-4 h-4" />}
                </Button>
                <div className="w-0 group-hover/volume:w-24 overflow-hidden transition-all duration-300">
                  <Slider
                    value={[player.muted ? 0 : player.volume]}
                    onValueChange={(val) => player.setVolume(val[0])}
                    max={100}
                    className="w-20"
                  />
                </div>
              </div>

              <div className="w-px h-8 bg-white/10 hidden md:block" />

              <Button
                variant="ghost"
                size="icon"
                className={cn("w-9 h-9 rounded-full", showQueue ? "text-primary bg-primary/10" : "text-muted-foreground hover:text-white")}
                onClick={() => setShowQueue(!showQueue)}
              >
                <ListMusic className="w-4 h-4" />
              </Button>

              <Button
                variant="ghost"
                size="icon"
                className="w-9 h-9 rounded-full text-muted-foreground hover:text-magenta-500 hover:bg-magenta-500/10"
              >
                <Heart className="w-4 h-4" />
              </Button>

            </div>
          </div>

          {/* Ambient Glow */}
          <div className="absolute inset-0 bg-gradient-to-r from-cyan-500/5 via-primary/5 to-magenta-500/5 opacity-0 group-hover:opacity-100 transition-opacity duration-700 pointer-events-none -z-10" />
        </div>
      </div>
    </>
  );
}
