<template>
    <div>
        <h1>Watch Page</h1>
        <div v-if="mediaId">
            <p>Media Type: {{ mediaType }}</p>
            <p>Media ID: {{ mediaId }}</p>
            <p>Media Hash: {{ mediaHash }}</p>
            <p>Episode: {{ episode }}</p>

            <div v-if="hlsUrls">
                <Player :id="mediaId.toString().concat(episode?.toString() || '')" :urls="hlsUrls" :episode="episode"
                    :nextEpisodeButton="true" />
            </div>

            <!-- Loading and Error States -->
            <div v-if="isLoading" class="loading">Loading video...</div>
            <div v-if="error" class="error">Error loading video: {{ error }}</div>
        </div>
        <div v-else>
            <p>No media selected.</p>
        </div>
    </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { Player } from '~/components/ui/player'
import { video, type KodikVideoLinks } from '~/openapi/extractor'

const route = useRoute()
const mediaType = route.query.mediaType
const mediaId = route.query.mediaId
const mediaHash = route.query.mediaHash
const episode = route.query.episode

const results = ref<KodikVideoLinks | null>(null)
const isLoading = ref(false)
const error = ref<unknown>(null)
const hlsUrls = ref<any>(null)

watchEffect(async () => {
    if (!mediaType || !mediaId || !mediaHash || !episode) return

    try {
        isLoading.value = true
        error.value = null

        const videoParams: any = {
            mediaType: mediaType as string,
            mediaId: mediaId as string,
            mediaHash: mediaHash as string,
            episode: Number(episode as string),
            quality: '360',
        }

        const response = await video(videoParams)
        results.value = response?.data || null

        if (results.value?.links) {
            hlsUrls.value = Object.entries(results.value.links).map(([quality, links], index) => {
                return {
                    html: quality,
                    url: links.find(link => link.src?.includes('.m3u8') || link.type?.includes('hls'))?.src,
                    default: index === 0
                }
            })

        }
    } catch (err) {
        error.value = err
        console.error('Failed to fetch video:', err)
    } finally {
        isLoading.value = false
    }
})
</script>
