<script lang="ts" setup>
const props = defineProps({
  isOpen: {
    type: Boolean,
    required: false,
  },
})

const emit = defineEmits({
  close: () => true,
  select: (titles: TitlesTemplate) => titles,
})

const toast = useToast()
const loginState = useLoginState()
const isRealOpen = computed(() => props.isOpen)

const pagination = reactive({
  page: 1,
  pageSize: 15,
})
const selectedTitle = ref<TitlesTemplate | null>(null)

const {
  data: userTitlesTemplate,
  status: userTitlesTemplateStatus,
  refresh: refreshUserTitlesTemplate,
} = useAsyncData(
  'userTitlesTemplate',
  () =>
    useFetchWrapped<
      PagedDataRequest & AuthedRequest & { process_status: 0 | 1 },
      BaseResponse<PagedData<TitlesTemplate>>
    >('App.User_UserTitles.GetList', {
      token: loginState.token!,
      user_id: loginState.user.id,
      to_user_id: loginState.user.id,
      page: pagination.page,
      perpage: pagination.pageSize,
      process_status: 1,
    }),
  {
    watch: [pagination],
  }
)

const handleClose = () => {
  if (props.isOpen) {
    emit('close')
  } else {
    emit('close')
  }
}

const handleSubmit = () => {
  if (!selectedTitle.value) {
    toast.add({
      title: '请选择片头',
      description: '请选择一个片头',
      color: 'error',
      icon: 'i-tabler-circle-x',
    })
    return
  }
  emit('select', selectedTitle.value)
  handleClose()
}
</script>

<template>
  <UModal
    v-model:open="isRealOpen"
    :ui="{ content: 'w-full sm:max-w-3xl' }"
    @close="handleClose"
  >
    <template #content>
      <UCard>
        <template #header>
          <div class="flex items-center justify-between">
            <h3
              class="text-base font-semibold leading-6 text-gray-900 dark:text-white"
            >
              视频片头选择器
            </h3>
            <UButton
              class="-my-1"
              color="neutral"
              icon="i-tabler-x"
              variant="ghost"
              @click="handleClose"
            />
          </div>
        </template>

        <div>
          <div class="grid w-full grid-cols-2 gap-4 sm:grid-cols-3">
            <div
              v-for="(titles, i) in userTitlesTemplate?.data.items"
              :key="`user-titles-${titles.id}`"
              :class="{
                'border-primary shadow-md': selectedTitle?.id === titles.id,
                'border-neutral-200 dark:border-neutral-700':
                  selectedTitle?.id !== titles.id,
              }"
              class="relative flex w-full cursor-pointer select-none flex-col items-center justify-center gap-2 overflow-hidden rounded-md border bg-white transition-all duration-150 dark:border-2 dark:bg-neutral-800"
              @click="selectedTitle = titles"
            >
              <div
                :class="{
                  'bg-primary-50': selectedTitle?.id === titles.id,
                }"
                class="relative aspect-video w-full overflow-hidden border-b bg-neutral-100 object-cover transition-all duration-150 dark:border-neutral-700 dark:bg-neutral-800"
              >
                <NuxtImg :src="titles.opening_url" />
                <UIcon
                  v-if="selectedTitle?.id === titles.id"
                  class="text-primary absolute right-1 top-1 text-lg"
                  name="i-tabler-check"
                />
              </div>
              <div class="flex w-full flex-col gap-1 px-2 pb-2">
                <div class="flex items-center justify-between">
                  <span
                    class="line-clamp-1 text-sm font-medium text-neutral-800 dark:text-neutral-300"
                  >
                    {{ titles.title }}
                  </span>
                  <span
                    class="text-xs font-medium text-neutral-300 dark:text-neutral-500"
                  >
                    ID:{{ titles.id }}
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="flex justify-end">
            <UPagination
              v-if="(userTitlesTemplate?.data.total || 0) > 0"
              v-model:page="pagination.page"
              :page-count="pagination.pageSize"
              :total="userTitlesTemplate?.data.total || 0"
              class="pt-4"
            />
          </div>
        </div>

        <template #footer>
          <div class="flex items-center justify-between">
            <div>
              <p class="select-none text-xs font-medium opacity-50">
                如果此处没有您的片头，请在
                <a
                  class="text-primary"
                  href="/generation/materials"
                  target="_blank"
                >
                  片头模版库
                </a>
                页面确认已经制作完毕
              </p>
            </div>
            <div class="flex items-center gap-4">
              <UButton
                color="neutral"
                label="取消"
                variant="ghost"
                @click="handleClose"
              />
              <UButton
                color="primary"
                label="选择"
                variant="solid"
                @click="handleSubmit"
              />
            </div>
          </div>
        </template>
      </UCard>
    </template>
  </UModal>
</template>

<style scoped></style>
