<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

        if (queueSongs.length == 0) {
            playNext()
        }
    })

    $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

        if (audioController) {
            audioController.pause()
            audioController.currentTime = 0
        }
    }

    function seek(e: Event) {
        const target = e.target as HTMLInputElement
        const seekTime = parseFloat(target.value)
        playerInfo.currentTime = seekTime
        if (audioController) {
            audioController.currentTime = seekTime
        }
    }
</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-full flex-col items-start justify-start gap-4 p-2 lg:w-[30vw]">
            <p>{formatTime(playerInfo.currentTime)} - {formatTime(playerInfo.duration)}</p>
            <input type="range" min="0" max={playerInfo.duration} step="0.1" value={playerInfo.currentTime} class="w-full accent-blue-500" oninput={seek} />
            <div class="flex w-full flex-row items-center justify-center gap-6">
                <button
                    class="rounded-md border border-dark-pine-muted p-2 hover:scale-105 active:scale-90 dark:bg-dark-pine-blue"
                    onclick={() => (playerInfo.playing ? audioController?.pause() : audioController?.play())}>{playerInfo.playing ? "Pause" : "Unpause"}</button
                >
                <button class="rounded-md border border-dark-pine-muted p-2 hover:scale-105 active:scale-90 dark:bg-dark-pine-blue" onclick={playNext}>Next</button>
            </div>
        </div>
        <img class="absolute right-1 bottom-1" src="/api/room/qrcode?room=1000&pin=1234" />
        <!-- @PERETTO fix here pls -->
    </div>
{/if}
