<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"
                    :episodeButton="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 = computed(() => route.query.mediaType as string)
const mediaId = computed(() => route.query.mediaId as string)
const mediaHash = computed(() => route.query.mediaHash as string)
const episode = computed(() => Number(route.query.episode as string))

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

watchEffect(async () => {
    try {
        isLoading.value = true
        error.value = null

        const videoParams: any = {
            mediaType: mediaType.value,
            mediaId: mediaId.value,
            mediaHash: mediaHash.value,
            episode: episode.value,
            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>
