<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 loginState = useLoginState()
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)
    })
}

const onRetryClick = (course: resp.gen.CourseGenItem) => {
  useFetchWrapped<
    req.gen.CourseGenCreate & AuthedRequest,
    BaseResponse<resp.gen.CourseGenCreate>
  >('App.Digital_Convert.Create', {
    token: loginState.token!,
    user_id: loginState.user.id,
    task_title: course.title,
    gen_server: 'main',
    speed: 2 - course.speed,
    ppt_url: course.ppt_url,
    digital_human_id: course.digital_human_id,
    custom_video: '[]',
    opening_url: course.opening_url || '',
    ending_url: course.opening_url || '',
  }).then(
    (res) => {
      if (res.data.record_status === 1) {
        toast.add({
          title: '重试已提交',
          description: '已加入生成队列',
          color: 'green',
          icon: 'i-tabler-check',
        })
        // delete
        emit('delete', course.task_id)
      } else {
        toast.add({
          title: '提交重试失败',
          description: res.msg || '未知错误',
          color: 'red',
          icon: 'i-tabler-alert-triangle',
        })
      }
    },
    (err) => {
      toast.add({
        title: '提交重试失败',
        description: err.message || '未知错误',
        color: 'red',
        icon: 'i-tabler-alert-triangle',
      })
    }
  )
}
</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 group">
      <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
        v-if="isDownloadable"
        class="absolute inset-0 bg-black/10 backdrop-blur-md flex justify-center items-center opacity-0 group-hover:opacity-100 duration-300"
      >
        <div
          class="rounded-full w-14 aspect-square bg-gray-300/50 backdrop-blur-md flex justify-center items-center cursor-pointer"
          @click="isPreviewModalOpen = true"
        >
          <Icon
            name="i-tabler-play"
            class="text-white text-3xl"
          />
        </div>
      </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}` : ''
              )
            "
          >
            {{ isFailed ? '复制错误报告' : '复制 ID' }}
          </button>
        </p>
      </div>
      <div class="flex items-center gap-1">
        <UButtonGroup>
          <!-- <UButton
            v-if="isFailed"
            color="white"
            :disabled="!isFailed"
            label="重试"
            leading-icon="i-tabler-refresh"
            size="xs"
            @click="onRetryClick(course)"
          />
          <UButton
            v-else
            color="white"
            :disabled="!isDownloadable"
            label="下载"
            leading-icon="i-tabler-download"
            size="xs"
            @click="onCombination"
          /> -->
          <UButton
            color="white"
            :disabled="!isFailed && !isDownloadable"
            :label="isFailed ? '重试' : isDownloadable ? '下载' : '生成中'"
            :leading-icon="isFailed ? 'i-tabler-refresh' : 'i-tabler-download'"
            size="xs"
            @click="
              () => {
                if (isFailed) {
                  onRetryClick(course)
                } else {
                  onCombination()
                }
              }
            "
          />
          <!-- retry -->
          <UDropdown
            v-model:open="isDropdownOpen"
            :items="[
              [
                {
                  label: '下载原视频',
                  icon: 'i-tabler-file-plus',
                  disabled: !isDownloadable,
                  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"
      :ui="{ width: 'w-full sm:max-w-4xl' }"
    >
      <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>
