import { useState, useEffect } from 'react'
import { Play, Pause, SkipBack, SkipForward } from 'lucide-react'
import { Button } from "@/components/ui/button"
import { useParams } from 'react-router-dom';
import { getRoundData, progressGame } from '@/firebase/game';
import { Layout } from '../layout/Layout';

interface FullSpotifyTrack {
    id: string;
    name: string;
    artist: string;
    album: string;
    previewUrl: string;
    // Add other properties as needed
}

export default function MusicPlaybackScreen({ isSpectator = false }: { isSpectator: boolean }) {
    const [songs, setSongs] = useState<FullSpotifyTrack[]>([]);
    const [currentSongIndex, setCurrentSongIndex] = useState(0);
    const [isPlaying, setIsPlaying] = useState(false);
    const { gameId } = useParams<{ gameId: string }>();

    useEffect(() => {
        const fetchSongs = async () => {
            if (gameId) {
                const roundData = await getRoundData(gameId);
                setSongs(roundData.tracks);
            }
        };
        fetchSongs();
    }, [gameId]);

    useEffect(() => {
        // Load Spotify Embedded Player script
        const script = document.createElement('script');
        script.src = 'https://open.spotify.com/embed-podcast/iframe-api/v1';
        script.async = true;
        document.body.appendChild(script);

        return () => {
            document.body.removeChild(script);
        };
    }, []);

    useEffect(() => {
        if (isSpectator) {
            // Automatically play music for spectators
            setIsPlaying(true);
        }
    }, [isSpectator]);

    const togglePlayPause = () => {
        setIsPlaying(!isPlaying);
        const iframe = document.querySelector('iframe');
        if (iframe) {
            iframe.contentWindow?.postMessage({ command: isPlaying ? 'pause' : 'play' }, '*');
        }
    };

    const goToPreviousSong = () => {
        if (currentSongIndex > 0) {
            setCurrentSongIndex(currentSongIndex - 1);
            setIsPlaying(false);
        }
    };

    const goToNextSong = () => {
        if (currentSongIndex < songs.length - 1) {
            setCurrentSongIndex(currentSongIndex + 1);
            setIsPlaying(false);
        }
    };

    const currentSong = songs[currentSongIndex];

    return (
        <Layout>
            <div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-b from-background to-secondary w-full max-w-2xl mx-auto">
                {currentSong && (
                    <iframe
                        style={{ borderRadius: '12px' }}
                        src={`https://open.spotify.com/embed/track/${currentSong.id}?utm_source=generator&theme=0`}
                        width="100%"
                        height="152"
                        frameBorder="0"
                        allowFullScreen
                        allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
                        loading="lazy"
                    ></iframe>
                )}
                <div className="p-6">
                    <h2 className="text-2xl font-bold text-foreground mb-2" aria-label="Song title">{currentSong?.name}</h2>
                    <p className="text-lg text-muted-foreground mb-4" aria-label="Artist name">{currentSong?.artist}</p>

                    <div className="flex justify-center items-center space-x-4 mt-4">
                        {currentSongIndex > 0 && (
                            <Button
                                variant="outline"
                                size="icon"
                                aria-label="Previous song"
                                onClick={goToPreviousSong}
                            >
                                <SkipBack className="h-4 w-4" />
                            </Button>
                        )}
                        <Button
                            variant="outline"
                            size="icon"
                            aria-label={isPlaying ? "Pause" : "Play"}
                            onClick={togglePlayPause}
                        >
                            {isPlaying ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
                        </Button>
                        {currentSongIndex < songs.length - 1 && (
                            <Button
                                variant="outline"
                                size="icon"
                                aria-label="Next song"
                                onClick={goToNextSong}
                            >
                                <SkipForward className="h-4 w-4" />
                            </Button>
                        )}
                    </div>
                </div>
                <div className="flex justify-center">
                    <Button onClick={() => progressGame(gameId as string)}>
                        Vote!
                    </Button>
                </div>
            </div>
        </Layout>
    );
}

i want to use the song preview for spotify instead of the full song. because that contains the most exited part of the song most of the time