<script lang="ts">
    import QueueSlider from "$lib/components/QueueSlider.svelte"
    import { type Song } from "$lib/types"
    import { onMount } from "svelte"
    import type { FetchError } from "$lib/types"
    import { getQueueSongs, getStreamingUrl, triggerPlayNext } from "$lib/utils.js"
    import Error from "$lib/components/Error.svelte"

    let { data } = $props()

    let queueSongs = $state<Song[]>([])
    let playingIndex = $state<number>(0)
    let returnError = $state<FetchError | null>()

    let currentPlaying = $derived<Song>(queueSongs[playingIndex])
    let audioController = $state<HTMLAudioElement>()

    let playerInfo = $state({
        playing: false,
        currentTime: 0,
        duration: 0,
    })

    async function playOnEnd() {
        let url = await getStreamingUrl(currentPlaying.uuid)
        if (audioController) {
            audioController.src = url
            await audioController.play()
        }
    }

    $effect(() => {
        if (audioController) {
            audioController.ontimeupdate = () => {
                playerInfo.currentTime = audioController?.currentTime || 0
            }
            audioController.onloadedmetadata = () => {
                playerInfo.duration = audioController?.duration || 0
            }
            audioController.onplay = () => {
                playerInfo.playing = true
            }
            audioController.onpause = () => {
                playerInfo.playing = false
            }
        }
    })

    onMount(async () => {
        let songs, index
        ;[returnError, songs, index] = await getQueueSongs(data.roomId)

        queueSongs = songs
        playingIndex = index
    })

    $effect(() => {
        playOnEnd()
    })

    const formatTime = (t: number) => {
        const min = Math.floor(t / 60)
        const sec = Math.floor(t % 60)
        return `${min}:${sec.toString().padStart(2, "0")}`
    }

    async function playNext() {
        let songs, index
        ;[returnError, songs, index] = await triggerPlayNext(data.roomId)

        if (returnError) return

        queueSongs = songs
        playingIndex = index
    }
</script>

{#if returnError}
    <Error {returnError} />
{:else}
    <div class="flex w-full flex-col items-center justify-center p-4 lg:p-10">
        <QueueSlider {queueSongs} {playingIndex} />

        <audio autoplay bind:this={audioController} hidden onended={playNext}></audio>

        <div class="flex w-[30vw] flex-col items-start justify-start gap-4 p-2">
            <p>{formatTime(playerInfo.currentTime)} - {formatTime(playerInfo.duration)}</p>
            <input type="range" min="0" max={playerInfo.duration} disabled step="0.1" value={playerInfo.currentTime} class="w-full accent-blue-500" />
            <div class="flex w-full flex-row items-center justify-center gap-6">
                <button onclick={audioController.pause}>Pause</button>
                <button onclick={playNext}>Next</button>
            </div>
        </div>
    </div>
{/if}
