<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 modal = useModal()
const loginState = useLoginState()

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 {
    modal.close()
  }
}

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

<template>
  <UModal
    :model-value="isOpen"
    :ui="{ width: 'w-full sm:max-w-3xl' }"
    @close="handleClose"
  >
    <UCard
      :ui="{
        ring: '',
        divide: 'divide-y divide-gray-100 dark:divide-gray-800',
      }"
    >
      <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="gray"
            icon="i-tabler-x"
            variant="ghost"
            @click="handleClose"
          />
        </div>
      </template>

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

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

<style scoped></style>
