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

interface Playlist {
  id: string;
  name: string;
  videoId: string;
  icon: string;
}

const LOFI_PLAYLISTS: Playlist[] = [
  { id: 'lofi-girl', name: 'lofi hip hop radio', videoId: 'jfKfPfyJRdk', icon: '🎧' },
  { id: 'lofi-chill', name: 'Chill lofi', videoId: '5qap5aO4i9A', icon: '🎵' },
  { id: 'lofi-synth', name: 'Synthwave lofi', videoId: 'MVPTmgNG4x0', icon: '🌃' },
];

export default function MusicPlayer() {
  const [activeId, setActiveId] = useState<string>('lofi-girl');
  const [volume, setVolume] = useState(0.3);
  const [started, setStarted] = useState(false);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const playerRef = useRef<any>(null);
  const apiReady = useRef(false);

  // Load YouTube IFrame API on first user interaction
  const startPlayer = useCallback(() => {
    if (apiReady.current) return;
    apiReady.current = true;

    const tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    const first = document.getElementsByTagName('script')[0];
    first.parentNode?.insertBefore(tag, first);

    (window as any).onYouTubeIframeAPIReady = () => {
      const active = LOFI_PLAYLISTS.find((p) => p.id === activeId);
      if (!active) return;

      playerRef.current = new (window as any).YT.Player('kira-youtube-player', {
        height: '0',
        width: '0',
        videoId: active.videoId,
        playerVars: {
          autoplay: 1,
          controls: 0,
          loop: 1,
          playlist: active.videoId,
          enablejsapi: 1,
          origin: window.location.origin,
          modestbranding: 1,
        },
        events: {
          onReady: (e: any) => {
            e.target.setVolume(volume * 100);
            e.target.playVideo();
          },
        },
      });
    };
  }, [activeId, volume]);

  // Handle play button click (first user gesture)
  const handlePlay = () => {
    if (!started) {
      setStarted(true);
      startPlayer();
    }
  };

  // Change station
  const changeStation = (id: string) => {
    setActiveId(id);
    if (playerRef.current && (window as any).YT) {
      const active = LOFI_PLAYLISTS.find((p) => p.id === id);
      if (active) {
        playerRef.current.loadVideoById(active.videoId);
        playerRef.current.setVolume(volume * 100);
        playerRef.current.playVideo();
      }
    }
  };

  // Volume
  useEffect(() => {
    if (playerRef.current) {
      playerRef.current.setVolume(volume * 100);
    }
  }, [volume]);

  return (
    <div className="p-4">
      <div className="flex items-center justify-between mb-3">
        <h3 className="text-sm font-bold text-kira-plum flex items-center gap-2">
          <span>🎶</span> Lo-Fi
        </h3>
        <div className="flex items-center gap-2">
          <span className="text-xs text-kira-violet/50">vol</span>
          <input
            type="range"
            min="0"
            max="1"
            step="0.05"
            value={volume}
            onChange={(e) => setVolume(parseFloat(e.target.value))}
            className="w-20 accent-kira-pink"
          />
        </div>
      </div>

      <div className="flex gap-2 mb-3 flex-wrap">
        {LOFI_PLAYLISTS.map((p) => (
          <button
            key={p.id}
            onClick={() => started ? changeStation(p.id) : setActiveId(p.id)}
            className={`flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-medium transition-all ${
              activeId === p.id && started
                ? 'bg-kira-lav text-white shadow-md'
                : 'bg-white/50 text-kira-plum/60 hover:bg-kira-glow'
            }`}
          >
            <span>{p.icon}</span>
            <span className="hidden sm:inline">{p.name}</span>
          </button>
        ))}
      </div>

      {/* Hidden YouTube player container */}
      <div id="kira-youtube-player" ref={wrapperRef} className="hidden" />

      {/* Play button / status */}
      <div className="relative rounded-xl overflow-hidden bg-white/30" style={{ height: 60 }}>
        {!started ? (
          <button
            onClick={handlePlay}
            className="w-full h-full flex items-center justify-center gap-2 text-kira-plum/50 hover:text-kira-plum/80 hover:bg-white/20 transition-all"
          >
            <span className="text-lg">▶️</span>
            <span className="text-sm font-medium">Start Lo-Fi</span>
          </button>
        ) : (
          <div className="w-full h-full flex items-center justify-center text-kira-plum/40 text-xs gap-2">
            <span className="w-2 h-2 rounded-full bg-kira-mint animate-pulse inline-block" />
            <span>playing {LOFI_PLAYLISTS.find((p) => p.id === activeId)?.name}</span>
          </div>
        )}
      </div>
    </div>
  );
}
