<script setup lang="ts">
import EpisodeThumb from '@/components/EpisodeThumb.vue'
import MediaInfo from '@/components/MediaInfo.vue'
import jfapi, { type Item, type MediaStream } from '@/jfapi'
import { onBeforeMount, ref } from 'vue'
import { useRoute, RouterLink } from 'vue-router'

const route = useRoute()

const itemId = String(route.params.id)

const item = ref<Item>()
const directors = ref<string[]>([])
const writers = ref<string[]>([])
const selectSubTrack = ref<MediaStream>()
const selectAudioTrack = ref<MediaStream>()
const nextUp = ref<Item>()
const numAudioStreams = ref(0)
const VideoStream = ref<MediaStream>()
const AudioStreams = ref<MediaStream[]>([])
const SubtitleStreams = ref<MediaStream[]>([])
onBeforeMount(() => {
  jfapi.GetItem(itemId).then((data) => {
    if (data === null) {
      // error
    } else {
      item.value = data
      if (item.value.IsFolder) {
        console.log('Item is a Series')
        // item is a full series
        jfapi.GetNextUpInSeries(item.value.Id || '').then((data) => {
          if (data?.Items && data.Items.length > 0) {
            nextUp.value = data.Items[0]
          } else {
            jfapi.GetFirstEpisode(item.value?.Id || '').then((data) => {
              if (data?.Items) {
                nextUp.value = data.Items[0]
              }
            })
          }
        })
      }
    }
    if (item.value !== undefined && item.value.MediaStreams !== undefined) {
      for (const stream of item.value.MediaStreams) {
        if (stream.Type.toLowerCase() === 'video') {
          VideoStream.value = stream
        } else if (stream.Type.toLowerCase() === 'audio') {
          AudioStreams.value.push(stream)
          numAudioStreams.value++
          if (stream.IsForced && !selectAudioTrack.value?.DisplayTitle.includes('Forced')) {
            selectAudioTrack.value = stream
          } else if (
            stream.IsDefault &&
            !selectAudioTrack.value?.DisplayTitle.includes('Forced') &&
            !selectAudioTrack.value?.DisplayTitle.includes('Default')
          ) {
            selectAudioTrack.value = stream
          }
        } else if (stream.Type.toLowerCase() === 'subtitle') {
          SubtitleStreams.value.push(stream)
          if (stream.IsForced && !selectSubTrack.value?.DisplayTitle.includes('Forced')) {
            selectSubTrack.value = stream
          } else if (
            stream.IsDefault &&
            !selectSubTrack.value?.DisplayTitle.includes('Forced') &&
            !selectSubTrack.value?.DisplayTitle.includes('Default')
          ) {
            console.log(stream)
            selectSubTrack.value = stream
          }
        }
      }
      for (const person of item.value.People) {
        if (person.Type.toLowerCase() === 'director') {
          directors.value.push(person.Name)
        } else if (person.Type.toLowerCase() === 'writer') {
          writers.value.push(person.Name)
        }
      }
    }
    console.log(writers.value, directors.value)
  })
})

const arrayRange = (start: number, stop: number) =>
  Array.from({ length: (stop - start) / 1 }, (value, index) => start + index * 1)
</script>

<template>
  <div
    v-if="item"
    class="container"
    :style="{
      backgroundAttachment: 'fixed',
      backgroundSize: 'cover',
      backgroundImage: `url(${
        item.ParentBackdropItemId && item.ParentBackdropImageTags
          ? jfapi.FullBackdropImageUrl(
              item.ParentBackdropItemId,
              item.ParentBackdropImageTags[0],
              0,
            )
          : jfapi.FullBackdropImageUrl(item.Id, item.BackdropImageTags[0], 0)
      })`,
    }"
  >
    <div class="content-wrapper">
      <div class="item-info">
        <div class="media-title">
          <div class="logo">
            <img
              v-if="item.ImageTags.Logo || item.ParentLogoImageTag"
              :src="`${
                item.ParentLogoImageTag && item.ParentLogoItemId
                  ? jfapi.LogoImageUrl(item.ParentLogoItemId, item.ParentLogoImageTag)
                  : jfapi.LogoImageUrl(item.Id, item.ImageTags.Logo || '')
              }`"
              alt=""
            />
            <div class="title" v-else>{{ item.SeriesName ? item.SeriesName : item.Name }}</div>
            <MediaInfo :itemId="item.Id" :endsAt="item.Type !== 'Series'" size="lg" />
          </div>
        </div>
        <div class="info-wrapper">
          <div class="section">
            <div :class="`detail-buttons ${!item.IsFolder ? '' : 'wide'}`">
              <div class="play-button">
                <RouterLink :to="`/play/${item.Id}`">
                  <button class="primary-button">
                    <font-awesome-icon icon="fa-solid fa-play" size="md" />Play Now
                  </button>
                </RouterLink>
              </div>
              <div class="user-buttons">
                <div class="watched">
                  <font-awesome-icon icon="fa-solid fa-check" size="xl" class="clickable" />
                </div>
                <div class="favorited">
                  <font-awesome-icon :icon="['far', 'heart']" size="xl" class="clickable" />
                </div>
              </div>
            </div>
            <div class="media-streams" v-if="item.MediaStreams !== undefined">
              <div class="info-item">
                <div class="stream-type">Video</div>
                <div class="stream-value">{{ VideoStream?.DisplayTitle }}</div>
              </div>
              <div class="info-item">
                <div class="stream-type">Audio</div>
                <div class="stream-selector" v-if="AudioStreams.length > 1">
                  <select name="audio-stream-select" :id="`${item?.Id}-audio-select`">
                    <option
                      :value="`${AudioStreams[i].DisplayTitle}`"
                      v-for="i in arrayRange(0, AudioStreams.length)"
                      :key="`audio-stream-${i}`"
                    >
                      {{ AudioStreams[i].DisplayTitle }}
                    </option>
                  </select>
                </div>
                <div class="stream-value" v-else>{{ AudioStreams[0].DisplayTitle }}</div>
              </div>
              <div class="info-item">
                <div class="stream-type">Subtitles</div>
                <div class="stream-selector">
                  <select
                    name="subtitle-stream-select"
                    :id="`${item?.Id}-subtitle-select`"
                    v-if="SubtitleStreams.length > 0"
                  >
                    <option value="Off">Off</option>
                    <option
                      v-for="i in arrayRange(0, SubtitleStreams.length)"
                      :value="`${SubtitleStreams[i]?.DisplayTitle}`"
                      :selected="SubtitleStreams[i]?.DisplayTitle === selectSubTrack?.DisplayTitle"
                      :key="`subtitle-stream-${i}`"
                    >
                      {{ SubtitleStreams[i]?.DisplayTitle }}
                    </option>
                  </select>
                  <div class="stream-value" v-else>None</div>
                </div>
              </div>
            </div>
          </div>
          <div class="title episode-title" v-if="item.Type === 'Episode'">
            {{ `S${item.ParentIndexNumber}:E${item.IndexNumber} - ${item.Name}` }}
          </div>
          <blockquote class="tagline" v-if="item?.Taglines.length > 0">
            {{ item?.Taglines[0] }}
          </blockquote>
          <div class="overview">
            {{ item?.Overview }}
          </div>
          <div class="misc-info">
            <div v-if="item.Genres.length > 0" class="info-item">
              <div class="info-type">Genre</div>
              <div class="info-value">{{ item?.Genres.join(', ') }}</div>
            </div>
            <div v-if="directors.length > 0" class="info-item">
              <div class="info-type">{{ 'Director' + (directors.length > 1 ? 's' : '') }}</div>
              <div class="info-value">{{ directors.join(', ') }}</div>
            </div>
            <div v-if="writers.length > 0" class="info-item">
              <div class="info-type">{{ 'Writer' + (writers.length > 1 ? 's' : '') }}</div>
              <div class="info-value">{{ writers.join(', ') }}</div>
            </div>
            <div v-if="item.Studios.length > 0" class="info-item">
              <div class="info-type">{{ 'Studio' + (item?.Studios.length > 1 ? 's' : '') }}</div>
              <div class="info-value">{{ item?.Studios.map((s) => s.Name).join(', ') }}</div>
            </div>
          </div>
          <div class="next-up" v-if="nextUp">
            Next Up
            <EpisodeThumb :item="nextUp" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.container {
  min-height: 100vh;
}
.content-wrapper {
  width: 95%;
  margin: auto;
  padding: 3em 0;
}
.subheading {
  width: 70%;
}
.item-info {
  padding: 3em 4em;
  width: 800px;
  min-height: 90vh;
  background: rgba(0, 0, 0, 0.4);
  color: rgba(255, 255, 255, 0.5);
  border-radius: 16px;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: var(--color-text);
}
.info-wrapper {
  display: flex;
  flex-direction: column;
  align-items: baseline;
  justify-content: space-between;
  gap: 1.5em;
  width: 95%;
  margin: 2em auto;
}
.media-title {
  min-height: 200px;
  max-height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.title {
  font-size: 52px;
  font-weight: bold;
  font-family: 'DM Sans', sans-serif;
  text-align: center;
  width: 90%;
}
.title.episode-title {
  font-size: 24px;
  font-weight: 500;
  text-align: left;
}
.logo {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2em;
  margin: auto 0;
}
.logo img {
  max-width: 700px;
  max-height: 230px;
}
.section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
.detail-buttons {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-direction: column;
  gap: 1em;
  margin-left: 2em;
  min-width: 200px;
}
.wide {
  flex-direction: row;
  gap: 3em;
}
.user-buttons {
  display: flex;
  justify-content: space-between;
  gap: 2em;
}
.media-streams {
  display: flex;
  flex-direction: column;
}
.media-streams .info-item {
  display: flex;
  align-items: center;
  gap: 1em;
}
.stream-type {
  text-align: right;
  width: 100px;
  flex-shrink: 0;
}
.stream-value {
  font-size: 14px;
  word-wrap: break-word;
  max-width: 300px;
}
.stream-selector {
  margin: 0.2em;
  max-width: 300px;
}
.stream-selector select {
  width: 100%;
}
.misc-info {
  display: flex;
  flex-direction: column;
}
.info-item {
  display: flex;
  align-items: baseline;
  gap: 1em;
}
.misc-info .info-type {
  text-align: right;
  width: 70px;
}
.misc-info .info-value {
  font-size: 14px;
  max-width: 500px;
}
.tagline {
  position: relative;
  padding-left: 1em;
}
.tagline::before {
  content: '\201C';
  font-size: 156px;
  position: absolute;
  top: -80px;
  left: -10px;
  color: rgba(0, 0, 0, 0.4);
  z-index: -1;
  font-family: 'Georgia', Times, serif;
}
</style>
