<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="hlsUrl">
                <Player :id="mediaId.toString()" :src="hlsUrl" />
            </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 KodikTranslationDTO, type KodikVideoLinks, type VideoParams } 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 hlsUrl = ref<string | null>(null)

const playerOptions = ref({
    autoplay: false,
    controls: true,
    responsive: true,
    fluid: true,
    sources: [{
        src: hlsUrl.value,
        type: 'application/x-mpegURL'
    }]
})

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

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

        const translationDto: KodikTranslationDTO = {
            mediaType: mediaType as string,
            mediaId: mediaId as string,
            mediaHash: mediaHash as string,
        }

        const videoParams: VideoParams = {
            translationDTO: translationDto,
            episode: Number(episode as string),
            quality: '360',
        }

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

        if (results.value?.links) {
            const qualities = Object.keys(results.value.links)
            const bestQuality = qualities.includes('360') ? '360' :
                qualities[0]

            const hlsLink = results.value.links[bestQuality ?? '360']?.find(link =>
                link.type?.includes('hls') || link.src?.includes('.m3u8')
            )
            console.log(bestQuality)

            if (hlsLink?.src) {
                hlsUrl.value = hlsLink.src
                if (playerOptions.value?.sources[0]) {
                    playerOptions.value.sources[0].src = hlsUrl.value
                }
            } else {
                throw new Error('No HLS stream found in response')
            }
        }
    } catch (err) {
        error.value = err
        console.error('Failed to fetch video:', err)
    } finally {
        isLoading.value = false
    }
})
</script>
