<script setup lang="ts">
import type { PropType } from 'vue'
import dayjs from 'dayjs'
import { useDownload } from '~/composables/useDownload'
import gsap from 'gsap'

const toast = useToast()
const { metaSymbol } = useShortcuts()

const srtEditor = ref()

const props = defineProps({
  course: {
    type: Object as PropType<resp.gen.CourseGenItem>,
    required: true,
  },
})
const emit = defineEmits(['delete'])

defineShortcuts({
  'p': {
    handler: () => {
      if (isDropdownOpen.value && isDownloadable.value) {
        isPreviewModalOpen.value = true
      }
    },
  },
  'meta_d': {
    handler: () => {
      if (isDropdownOpen.value && isDownloadable.value) {
        srtEditor.value.open()
        isDropdownOpen.value = false
      }
    },
  },
  'meta_s': {
    handler: async () => {
      if (isDropdownOpen.value && isDownloadable.value) {
        await startDownload(await fetchCourseSubtitleUrl(props.course), `眩生花微课_${props.course.title}_${props.course.task_id}.srt`)
      }
    },
  },
  'delete': {
    handler: () => {
      if (isDropdownOpen.value) {
        emit('delete', props.course.task_id)
      }
    },
  },
})

const isDropdownOpen = ref(false)
const isPreviewModalOpen = ref(false)

const stateDisplay = computed(() => {
  if (props.course.progress === -1) return {
    color: 'red',
    text: '失败',
  }
  if (props.course.progress === 100) return {
    color: 'green',
    text: '完成',
  }
  return {
    color: 'blue',
    text: !!props.course.progress ? `${tweenedGenerateProgress.value.toFixed(0)}%` : '队列中',
  }
})
const isFailed = computed(() => props.course.progress === -1)
const isDownloadable = computed(() => !isFailed.value && props.course.progress === 100)

const generateProgress = computed(() => {
  return props.course.progress || 0
})
const tweenedGenerateProgress = ref(0)
watch(generateProgress, (newValue) => {
  gsap.to(tweenedGenerateProgress, {
    duration: 5,
    value: newValue,
  })
}, {
  immediate: true,
})

const downloadProgress = ref(0)

const startDownload = async (
  url: string,
  filename: string,
) => {
  downloadProgress.value = 0

  const {
    download,
    progressEmitter,
  } = useDownload(url, filename)

  progressEmitter.on('done', () => {
    downloadProgress.value = 100
    toast.add({
      title: '下载完成',
      description: '资源下载已完成',
      color: 'green',
      icon: 'i-tabler-check',
    })
  })

  progressEmitter.on('progress', (progress) => {
    downloadProgress.value = progress
  })

  progressEmitter.on('error', err => {
    downloadProgress.value = 0
    toast.add({
      title: '下载失败',
      description: err.message || '下载失败，未知错误',
      color: 'red',
      icon: 'i-tabler-alert-triangle',
    })
  })

  download()
}

const copyTaskId = (extraMessage?: string) => {
  navigator.clipboard.writeText(props.course.task_id + (extraMessage ? ` ${extraMessage}` : ''))
  toast.add({
    title: '复制成功',
    description: '已复制任务 ID',
    color: 'green',
    icon: 'i-tabler-check',
  })
}

const isCombinationModalOpen = ref(false)
const combinationState = ref<0 | 1 | undefined>(0)

const onCombination = () => {
  isCombinationModalOpen.value = true
  combinationState.value = undefined
  useVideoSubtitleEmbedding(props.course.video_url, props.course.subtitle_url).then(src => {
    startDownload(src, `眩生花微课_${props.course.title}_${props.course.task_id}_combinated.mp4`)
    combinationState.value = 1
  }).catch(err => {
    toast.add({
      title: '嵌入字幕失败',
      description: err.message || '未知错误',
      color: 'red',
      icon: 'i-tabler-alert-triangle',
    })
    combinationState.value = 0
  }).finally(() => {
    setTimeout(() => {
      combinationState.value = 0
      isCombinationModalOpen.value = false
    }, 3000)
  })
}
</script>

<template>
  <div
    class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 hover:shadow transition overflow-hidden">
    <div class="relative w-full aspect-video">
      <NuxtImg class="w-full aspect-video object-cover pointer-events-none absolute inset-0" v-if="!!course.video_cover"
        :src="course.video_cover" alt="image" loading="lazy" />
      <div v-else
        class="absolute inset-0 bg-gradient-to-br from-purple-400 to-primary-400 flex justify-center items-center pattern">
        <Icon v-if="isFailed" class="text-white text-[64px] opacity-50" name="i-tabler-alert-triangle" />
        <Icon v-else class="text-white text-[64px] animate-pulse" name="i-tabler-photo-video" />
      </div>
      <div class="absolute inset-2 flex justify-end items-start">
        <UTooltip :prevent="course.progress > -1" :text="course.message || ''">
          <UBadge :color="stateDisplay.color" :variant="isFailed ? 'solid' : 'subtle'" class="shadow" size="sm">
            <Icon v-if="isFailed" class="text-base mr-0.5" name="i-tabler-alert-triangle" />
            {{ stateDisplay.text }}
          </UBadge>
        </UTooltip>
      </div>
    </div>
    <div class="px-2 pt-1 pb-2 flex justify-between">
      <div class="flex-1 overflow-hidden pt-1">
        <h1 :title="course.title"
          class="inline-flex items-center text-sm font-medium overflow-hidden text-ellipsis text-nowrap">
          <Icon class="text-base" name="i-tabler-book-2" />
          <span class="pl-0.5">{{ course.title }}</span>
        </h1>
        <p class="text-xs pt-0.5 text-neutral-400 space-x-2">
          <span>{{ dayjs(course.create_time * 1000).format('YYYY-MM-DD HH:mm:ss') }}</span>
          <button v-if="course.task_id" class="hover:text-primary font-medium" tabindex="-1" :title="course.task_id"
            @click="copyTaskId(isFailed ? `\n\n${course.message}\n${course.ppt_url}` : '')">
            复制ID
          </button>
        </p>
      </div>
      <div class="flex items-center gap-1">
        <UButtonGroup>
          <UButton color="white" :disabled="!isDownloadable" label="下载" leading-icon="i-tabler-download" size="xs"
            @click="onCombination" />
          <UDropdown v-model:open="isDropdownOpen" :items="[
            [{
              label: '下载原视频',
              icon: 'i-tabler-file-plus',
              click: () => startDownload(course.video_url, `眩生花微课_${props.course.title}_${props.course.task_id}.mp4`),
            }, {
              label: '预览课程',
              icon: 'i-tabler-play',
              shortcuts: ['P'],
              disabled: !isDownloadable,
              click: () => isPreviewModalOpen = true,
            }, {
              label: '编辑字幕',
              icon: 'i-solar-subtitles-linear',
              shortcuts: [metaSymbol, 'D'],
              disabled: !isDownloadable,
              click: () => {
                srtEditor.open()
                isDropdownOpen = false
              }
            }, {
              label: '下载字幕',
              icon: 'i-tabler-file-download',
              shortcuts: [metaSymbol, 'S'],
              disabled: !isDownloadable,
              click: async () => {
                await startDownload(await fetchCourseSubtitleUrl(course), `眩生花微课_${props.course.title}_${props.course.task_id}.srt`)
              }
            }], [{
              label: '删除记录',
              icon: 'i-tabler-trash-x',
              shortcuts: ['Delete'],
              click: () => emit('delete', course.task_id)
            }],
          ]" :popper="{ placement: 'bottom-end' }">
            <UButton :disabled="course.progress > 1 && course.progress < 100" color="white" size="xs"
              trailing-icon="i-tabler-dots" />
          </UDropdown>
        </UButtonGroup>
      </div>
    </div>
    <UModal v-model="isPreviewModalOpen">
      <UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
        <template #header>
          <div class="flex items-center justify-between">
            <div class="text-base font-semibold leading-6 text-gray-900 dark:text-white overflow-hidden">
              <p>微课视频预览</p>
              <p class="text-xs text-blue-500 w-full overflow-hidden text-nowrap text-ellipsis">
                {{ course.title }}
              </p>
            </div>
            <UButton class="-my-1" color="gray" icon="i-tabler-x" variant="ghost" @click="isPreviewModalOpen = false" />
          </div>
        </template>

        <video class="w-full rounded shadow" controls autoplay :src="course.video_url" />
      </UCard>
    </UModal>
    <UModal v-model="isCombinationModalOpen">
      <UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
        <template #header>
          <div class="flex items-center justify-between">
            <div class="text-base font-semibold leading-6 text-gray-900 dark:text-white overflow-hidden">
              <p>嵌入视频字幕</p>
              <p class="text-xs text-blue-500 w-full overflow-hidden text-nowrap text-ellipsis">
                {{ course.title }}
              </p>
            </div>
            <UButton class="-my-1" color="gray" icon="i-tabler-x" variant="ghost"
              @click="isCombinationModalOpen = false" />
          </div>
        </template>
        <UProgress animation="carousel" :value="combinationState" :max="[
          '嵌入字幕中',
          '合并完成，开始下载',
        ]">
          <template #step-0="{ step }">
            <span class="inline-flex items-center gap-1 text-emerald-500">
              <UIcon name="tabler:text-caption" /> {{ step }}
            </span>
          </template>

          <template #step-1="{ step }">
            <span class="inline-flex items-center gap-1 text-primary-500">
              <UIcon name="tabler:paperclip" /> {{ step }}
            </span>
          </template>
        </UProgress>
      </UCard>
    </UModal>
    <AigcGenerationSRTEditor ref="srtEditor" :course="course" />
  </div>
</template>

<style scoped></style>