<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Search } from '@icon-park/vue-next'
import { DataTableInst } from 'naive-ui'
import { useRouter } from 'vue-router'
import useTableScrollY from '@/composables/useTableScrollY'
import { usePagination } from '@/composables/usePagination.ts'
import CustomPagination from '@/components/custom-pagination/custom-pagination.vue'
import { createDatabaseColumn } from './columns.tsx'
import { DatabaseFormInterface, DatabaseItemInterface } from './type.d'
import EditDatabaseModal from './components/edit-database-modal.vue'
import { fetchDeleteDataBaseById, fetchGetDataBaseList, handleUpdateDataBase } from '@/apis/database.ts'

type DatabaseEditFormInterface = DatabaseFormInterface & { id: number }

const { t } = useI18n()

const router = useRouter()

const databaseListTableRef = useTemplateRef<DataTableInst>('databaseListTableRef')

const { pageContentWrapRef, tableContentY } = useTableScrollY(48 + 32 + 18 + 16 + 28)
const { paginationData, handlePageNoChange, handlePageSizeChange } = usePagination()

const searchDatabaseInputValue = ref('')
const isSearchEmptyList = ref(false)

const databaseList = ref<DatabaseItemInterface[]>([])
const databaseListLoading = ref(false)

const showEditDatabaseModal = ref(false)
const updateDatabaseBtnLoading = ref(false)
const currentEditDatabaseInfo = ref<DatabaseEditFormInterface>({
  id: 0,
  title: '',
  desc: '',
  dbType: '',
  dbHost: '',
  dbPort: 0,
  dbName: '',
  dbUsername: '',
  dbPassword: '',
})

const databaseColumns = createDatabaseColumn(handleDatabaseTableAction)

const emptyTableDataText = computed(() => {
  return isSearchEmptyList.value ? t('common_module.search_empty_data') : t('common_module.empty_data')
})

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

watch([() => paginationData.pageNo, () => paginationData.pageSize], async () => {
  await handleGetDatabaseList()
  databaseListTableRef.value?.scrollTo({ top: 0, behavior: 'smooth' })
})

onMounted(() => {
  handleGetDatabaseList()
})

async function handleGetDatabaseList() {
  databaseListLoading.value = true

  const res = await fetchGetDataBaseList<DatabaseItemInterface[]>({
    search: searchDatabaseInputValue.value,
    pagingInfo: paginationData,
  })

  if (res.code === 0) {
    databaseList.value = res.data
    paginationData.totalRows = res.pagingInfo?.totalRows || 0
    paginationData.totalPages = res.pagingInfo?.totalPages || 0
    isSearchEmptyList.value = !!searchDatabaseInputValue.value && paginationData.totalRows === 0
    databaseListLoading.value = false
  }
}

async function handleSearchDatabaseList() {
  paginationData.pageNo = 1
  await handleGetDatabaseList()
  databaseListTableRef.value?.scrollTo({ top: 0, behavior: 'smooth' })
}

function handleDatabaseTableAction(actionType: string, dbId: number) {
  switch (actionType) {
    case 'view':
      handleToDatabaseDetail(dbId)
      break
    case 'edit':
      handleShowEditDatabaseModal(dbId)
      break
    case 'delete':
      handleDeleteDatabaseById(dbId)
      break
  }
}

function handleToDatabaseDetail(dbId: number) {
  router.push({
    name: 'PersonalSpaceDBTable',
    params: { id: dbId },
  })
}

function handleShowEditDatabaseModal(dbId: number) {
  showEditDatabaseModal.value = true

  databaseList.value.forEach((item) => {
    if (item.id === dbId) {
      currentEditDatabaseInfo.value = item
    }
  })
}

function handleDeleteDatabaseById(dbId: number) {
  window.$message
    .ctWarning('', t('personal_space_module.knowledge_module.delete_knowledge_dialog_content'))
    .then(async () => {
      const res = await fetchDeleteDataBaseById(dbId)

      if (res.code === 0) {
        if (databaseList.value.length <= 1 && paginationData.pageNo === paginationData.totalPages) {
          paginationData.pageNo = paginationData.pageNo - 1 || 1
        }
        window.$message.success(t('common_module.delete_success_message'))
        await handleGetDatabaseList()
      }
    })
}

async function handleUpdateDatabase(databaseData: DatabaseEditFormInterface) {
  updateDatabaseBtnLoading.value = true

  const res = await handleUpdateDataBase(databaseData).finally(() => {
    updateDatabaseBtnLoading.value = false
  })

  if (res.code === 0) {
    showEditDatabaseModal.value = false
    window.$message.success(t('common_module.successful_update'))
    handleGetDatabaseList()
  }
}
</script>

<template>
  <div ref="pageContentWrapRef" class="h-full w-full">
    <div class="mb-[18px] flex justify-end">
      <n-input
        v-model:value="searchDatabaseInputValue"
        :placeholder="t('common_module.search')"
        class="w-[256px]!"
        @keyup.enter="handleSearchDatabaseList"
      >
        <template #suffix>
          <Search theme="outline" size="16" fill="#999" class="cursor-pointer" />
        </template>
      </n-input>
    </div>

    <div class="mb-4" :style="{ height: tableContentY + 48 + 'px' }">
      <n-data-table
        ref="databaseListTableRef"
        :loading="databaseListLoading"
        :bordered="true"
        :bottom-bordered="true"
        :single-line="false"
        :data="databaseList"
        :columns="databaseColumns"
        :max-height="tableContentY"
      >
        <template #empty>
          <div :style="{ height: tableContentY + 'px' }" class="flex items-center justify-center">
            <div class="flex flex-col items-center justify-center">
              <div
                class="mb-5 h-[68px] w-[68px]"
                :class="isSearchEmptyList ? 'bg-px-search_empty_list-png' : 'bg-px-empty_list-png'"
              />
              <p class="text-gray-font-color select-none">{{ emptyTableDataText }}</p>
            </div>
          </div>
        </template>
      </n-data-table>
    </div>

    <footer v-show="isLoadingPagination" class="flex justify-end">
      <CustomPagination
        :paging-info="paginationData"
        @update-page-no="handlePageNoChange"
        @update-page-size="handlePageSizeChange"
      />
    </footer>

    <EditDatabaseModal
      v-model:show-modal="showEditDatabaseModal"
      :database-detail="currentEditDatabaseInfo!"
      :btn-loading="updateDatabaseBtnLoading"
      @confirm="handleUpdateDatabase"
    />
  </div>
</template>
