<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import CustomIcon from '@/components/custom-icon/custom-icon.vue'
import CustomPagination, { PaginationInfo } from '@/components/custom-pagination/custom-pagination.vue'
import { createPersonalAppColumn } from './columns.ts'
import useTableScrollY from '@/composables/useTableScrollY.ts'
import {
  fetchDeleteApplication,
  fetchGetDebugApplicationInfo,
  fetchGetApplicationList,
  fetchSaveAgentApplication,
} from '@/apis/agent-application.ts'
import { PersonalAppConfigState } from '@/store/types/personal-app-config.ts'
import { copyToClip } from '@/utils/copy.ts'

const { t } = useI18n()

const router = useRouter()

const { pageContentWrapRef, tableContentY } = useTableScrollY(48 + 32 + 16 + 16 + 28)

const columns = createPersonalAppColumn(handleClickPersonalAppTableAction)

const pagingInfo = ref<PaginationInfo>({
  pageNo: 1,
  pageSize: 10,
  totalPages: 0,
  totalRows: 0,
})

const agentAppList = ref<PersonalAppConfigState[]>([])

const agentSearchInputValue = ref('')
const agentAppListTableLoading = ref(false)
const emptyTableText = ref(t('personal_space_module.agent_module.agent_list_module.empty_agent_list'))

const isLoadingPagination = computed(() => {
  return tableContentY.value > 0
})

onMounted(async () => {
  await handleGetApplicationList()
})

async function handleGetApplicationList() {
  agentAppListTableLoading.value = true
  const res = await fetchGetApplicationList<PersonalAppConfigState[]>({
    query: agentSearchInputValue.value,
    pagingInfo: pagingInfo.value,
  }).finally(() => (agentAppListTableLoading.value = false))

  if (res.code === 0) {
    agentAppList.value = res.data
    pagingInfo.value = res.pagingInfo as PaginationInfo
    emptyTableText.value = agentSearchInputValue.value
      ? t('personal_space_module.agent_module.agent_list_module.search_empty_agent_list')
      : t('personal_space_module.agent_module.agent_list_module.empty_agent_list')
  }
}

function handleClickPersonalAppTableAction(actionType: string, agentId: string) {
  switch (actionType) {
    case 'copyAgentId':
      handleCopyAgentId(agentId)
      break
    case 'openPublishDetail':
      handleOpenPublishDetail(agentId)
      break
    case 'edit':
      handleEditPersonalApp(agentId)
      break
    case 'copy':
      handleCopyPersonalApp(agentId)
      break
    case 'delete':
      handleDeletePersonalApp(agentId)
      break
  }
}

function handleCopyAgentId(agentId: string) {
  copyToClip(agentId)
  window.$message.success(t('common_module.copy_success_message'))
}

function handleOpenPublishDetail(agentId: string) {
  router.push({
    name: 'PersonalAppSetting',
    query: {
      tabKey: 'publish',
    },
    params: {
      agentId,
    },
  })
}

function handleEditPersonalApp(agentId: string) {
  router.push({
    name: 'PersonalAppSetting',
    params: {
      agentId,
    },
  })
}

async function handleCopyPersonalApp(agentId: string) {
  const res = await fetchGetDebugApplicationInfo<PersonalAppConfigState>(agentId)

  if (res.code === 0) {
    const payload = res.data

    payload.baseInfo.agentId = ''
    payload.baseInfo.agentTitle += t('personal_space_module.agent_module.agent_list_module.agent_copy')
    payload.baseInfo.agentPublishStatus = 'draft'

    await fetchSaveAgentApplication(payload)

    await handleGetApplicationList()
  }
}

function handleDeletePersonalApp(agentId: string) {
  window.$dialog.warning({
    title: t('personal_space_module.agent_module.agent_list_module.delete_agent_dialog_title'),
    content: t('personal_space_module.agent_module.agent_list_module.delete_agent_dialog_content'),
    negativeText: t('common_module.cancel_btn_text'),
    positiveText: t('common_module.confirm_btn_text'),
    onPositiveClick: async () => {
      const res = await fetchDeleteApplication(agentId)
      if (res.code === 0) {
        window.$message.success(t('common_module.delete_success_message'))
        agentAppList.value.length === 1 && (pagingInfo.value.pageNo = pagingInfo.value.pageNo - 1)
        await handleGetApplicationList()
      }
    },
  })
}

async function handleEnterKeypress(event: KeyboardEvent) {
  if (event.code === 'Enter' && !event.shiftKey) {
    event.preventDefault()

    await handleGetApplicationList()
  }
}

async function handleGetApplicationListUpdatePageNo(pageNo: number) {
  pagingInfo.value.pageNo = pageNo
  await handleGetApplicationList()
}

async function handleGetApplicationListUpdatePageSize(pageSize: number) {
  pagingInfo.value.pageNo = 1
  pagingInfo.value.pageSize = pageSize
  await handleGetApplicationList()
}
</script>

<template>
  <div ref="pageContentWrapRef" class="h-full">
    <div class="mb-4 flex justify-end">
      <NInput
        v-model:value="agentSearchInputValue"
        :placeholder="t('personal_space_module.agent_module.agent_list_module.search_agent_placeholder')"
        class="w-[256px]! h-[32px]!"
        @keypress="handleEnterKeypress"
      >
        <template #suffix>
          <CustomIcon
            icon="tdesign:search"
            class="cursor-pointer text-base text-[#999]"
            @click="handleGetApplicationList"
          />
        </template>
      </NInput>
    </div>

    <div class="mb-4" :style="{ height: tableContentY + 48 + 'px' }">
      <NDataTable
        :loading="agentAppListTableLoading"
        :bordered="true"
        :bottom-bordered="true"
        :single-line="false"
        :data="agentAppList"
        :columns="columns"
        :max-height="tableContentY"
        :scroll-x="1330"
      >
        <template #empty>
          <div :style="{ height: tableContentY + 'px' }" class="flex items-center justify-center">
            <div class="flex flex-col items-center justify-center">
              <img src="@/assets/images/empty.png" alt="empty" class="mb-2 h-[160px] w-[230px]" />
              <p class="text-base text-[#84868c]">{{ emptyTableText }}</p>
            </div>
          </div>
        </template>
      </NDataTable>
    </div>

    <footer v-show="isLoadingPagination" class="flex justify-end">
      <CustomPagination
        :paging-info="pagingInfo"
        @update-page-no="handleGetApplicationListUpdatePageNo"
        @update-page-size="handleGetApplicationListUpdatePageSize"
      />
    </footer>
  </div>
</template>
