<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Search } from '@icon-park/vue-next'
import CustomModal from '@/components/custom-modal/custom-modal.vue'
import { formatDateTime } from '@/utils/date-formatter'
import { fetchCreateDataBase, fetchGetDataBaseList } from '@/apis/database'
import {
  DatabaseFormInterface,
  DatabaseItemInterface,
  DatabaseTableInfoItem,
} from '@/views/personal-space/personal-database/type'
import CreateDatabaseModal from '@/views/personal-space/personal-database/components/create-database-modal.vue'

const emit = defineEmits<{
  (e: 'close'): void
}>()

const { t } = useI18n()

const showModal = defineModel<boolean>('showModal', { required: true })
const dbIds = defineModel<number[]>('dbIds', { required: true })

const isSearchEmptyList = ref(false)
const databaseListLoading = ref(true)
const refreshIconRotating = ref(false)
const searchQuery = ref('')
const showCreateDatabaseModal = ref(false)
const createDatabaseBtnLoading = ref(false)

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

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

const isAddedDBId = computed(() => (id: number) => {
  return dbIds.value?.includes(id)
})

const isDisabledAddBtn = computed(() => {
  return dbIds.value.length >= 1
})

const dbTableNameListText = (tableInfos: DatabaseTableInfoItem[]) => {
  let tableNameListText = ''

  if (Array.isArray(tableInfos)) {
    tableInfos.forEach((tableInfo) => {
      if (tableInfo.table_NAME) {
        tableNameListText += `${tableInfo.table_NAME}、`
      }
    })
    return tableNameListText.slice(0, -1)
  } else {
    return '---'
  }
}

watch(
  () => showModal.value,
  async (newValue) => {
    if (newValue) {
      searchQuery.value = ''
      await handleGetDatabaseList()
    }
  },
)

async function handleGetDatabaseList() {
  databaseListLoading.value = true
  const res = await fetchGetDataBaseList<DatabaseItemInterface[]>({
    search: searchQuery.value,
    pagingInfo: { pageSize: 9999999, pageNo: 1, totalRows: 0, totalPages: 0 },
  })

  if (res.code === 0) {
    databaseList.value = res.data
    databaseListLoading.value = false
  }
}

async function handleRefreshDatabaseList() {
  refreshIconRotating.value = true

  await handleGetDatabaseList().finally(() => (refreshIconRotating.value = false))
}

function handleShowCreateDatabaseModal() {
  showCreateDatabaseModal.value = true
}

async function handleCreateDatabase(databaseFormData: DatabaseFormInterface) {
  createDatabaseBtnLoading.value = true

  const res = await fetchCreateDataBase<{ id: number }>(databaseFormData).finally(
    () => (createDatabaseBtnLoading.value = false),
  )

  if (res.code === 0) {
    showCreateDatabaseModal.value = false
    const url = `${window.location.origin}/fe/personal-space/database/table/${res.data.id}`
    window.open(url, '_blank')
  }
}

function handleToDatabaseDetail(dbId: number) {
  const url = `${window.location.origin}/fe/personal-space/database/table/${dbId}`
  window.open(url, '_blank')
}

function handleAddDatabaseId(dbId: number, databaseTitle: string) {
  dbIds.value.push(dbId)
  window.$message.success(t('common_module.add_database_successfully', [databaseTitle]))
}

function handleRemoveDatabaseId(dbId: number, databaseTitle: string) {
  dbIds.value = dbIds.value.filter((id) => id !== dbId)
  window.$message.success(t('common_module.remove_database_successfully', [databaseTitle]))
}
</script>

<template>
  <CustomModal
    v-model:is-show="showModal"
    :title="''"
    :width="690"
    :height="675"
    :content-style="{ padding: '0 12px 24px' }"
    @close="emit('close')"
  >
    <template #header>
      <div class="flex items-center gap-[5px]">
        <div class="font-family-medium text-[18px] leading-none">
          {{ t('personal_space_module.database_module.add_database') }}
        </div>
        <div class="rounded-theme bg-[#F2F5F9] px-[10px] py-[2px] text-[12px]">
          {{
            t(
              'personal_space_module.agent_module.agent_setting_module.agent_config_module.only_one_database_can_be_added',
            )
          }}
        </div>
      </div>
    </template>

    <template #content>
      <div class="gap-4.5 flex w-full items-center justify-end px-3">
        <i
          class="iconfont icon-huanyihuan text-gray-font-color cursor-pointer transition-[rotate] duration-150 ease-in-out hover:opacity-80"
          :class="{ 'rotate-360': refreshIconRotating }"
          @click="handleRefreshDatabaseList"
        />

        <n-input
          v-model:value="searchQuery"
          :placeholder="t('common_module.search')"
          class="w-[214px]!"
          @keyup.enter="handleGetDatabaseList"
        >
          <template #prefix>
            <Search theme="outline" size="16" fill="#999" class="cursor-pointer" @click="handleGetDatabaseList" />
          </template>
        </n-input>

        <n-button type="primary" :focusable="false" :bordered="false" @click="handleShowCreateDatabaseModal">
          {{ t('personal_space_module.database_module.create_database') }}
        </n-button>
      </div>

      <n-virtual-list
        v-show="!databaseListLoading"
        class="mt-[18px] max-h-[533px] w-full pl-3"
        :item-size="136"
        :items="databaseList"
        key-field="id"
        items-style="padding-right: 12px;"
      >
        <template #default="{ item }: { item: DatabaseItemInterface }">
          <div
            :key="item.id"
            class="border-inactive-border-color hover:border-theme-color mb-4.5 relative flex h-[118px] w-full cursor-pointer items-center gap-4 overflow-hidden rounded-[10px] border px-4 py-3.5"
            @click="handleToDatabaseDetail(item.id)"
          >
            <div class="flex flex-1 flex-col overflow-hidden">
              <div class="flex flex-1">
                <div
                  class="h-9 w-9 flex-shrink-0 bg-[url('https://gsst-poe-sit.gz.bcebos.com/v1/icon/direct-db.svg')] bg-contain"
                />

                <div class="ml-3.5 flex flex-col items-start overflow-hidden">
                  <n-ellipsis class="flex-1">
                    <span class="font-600">{{ item.title }}</span>
                  </n-ellipsis>

                  <span class="text-gray-font-color mt-1 line-clamp-1 h-4 break-all text-xs">
                    {{ dbTableNameListText(item.tableInfos) }}
                  </span>

                  <div class="mt-3 flex items-center gap-4">
                    <span
                      v-show="!item.tableInfos?.length"
                      class="text-gray-font-color rounded-theme inline-block cursor-not-allowed bg-[#F7F7FA] px-2.5 py-[5px] text-[12px] leading-4"
                    >
                      {{ t('common_module.no_database_table') }}
                    </span>

                    <n-popover placement="bottom" content-style="padding: 16px 8px;" scrollable>
                      <template #trigger>
                        <span
                          v-show="item.tableInfos?.length"
                          class="text-theme-color rounded-theme inline-block cursor-pointer bg-[#F7F7FA] px-2.5 py-[5px] text-[12px] leading-4 hover:opacity-80"
                        >
                          {{ t('common_module.view_database_table') }}
                        </span>
                      </template>
                      <div>
                        <p class="text-gray-font-color h-5 px-4 text-[12px] leading-5">
                          {{ t('common_module.total_database_table', { count: item.tableInfos?.length || 0 }) }}
                        </p>

                        <n-scrollbar class="max-h-[200px] px-4">
                          <ul class="min-w-[300px]">
                            <li
                              v-for="(tableItem, index) in item.tableInfos"
                              :key="index"
                              class="text-font-color flex h-[50px] items-center gap-2.5 border-b border-[#F4F4F4] text-xs"
                            >
                              <n-ellipsis class="max-w-[400px]">
                                <span>{{ tableItem.table_NAME }}</span>
                              </n-ellipsis>
                            </li>
                          </ul>
                        </n-scrollbar>
                      </div>
                    </n-popover>

                    <span class="text-gray-font-color text-[12px]">
                      {{ t('common_module.modified_time') }}:
                      {{ formatDateTime(item.modifiedTime, 'YYYY-MM-DD') || '--' }}
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <n-button
              v-show="!isAddedDBId(item.id)"
              class="min-w-17!"
              :bordered="isDisabledAddBtn"
              :type="isDisabledAddBtn ? '' : 'primary'"
              :disabled="isDisabledAddBtn"
              @click.stop="handleAddDatabaseId(item.id, item.title)"
            >
              {{ t('common_module.add') }}
            </n-button>

            <n-button
              v-show="isAddedDBId(item.id)"
              class="min-w-17!"
              type="error"
              ghost
              @click.stop="handleRemoveDatabaseId(item.id, item.title)"
            >
              {{ t('common_module.remove') }}
            </n-button>

            <span
              v-if="item.example"
              class="bg-theme-color absolute -right-[18px] -top-[4px] z-10 rotate-45 px-[16px] pt-[6px] text-[10px] text-white"
            >
              {{ t('common_module.example') }}
            </span>
          </div>
        </template>
      </n-virtual-list>

      <div v-show="databaseListLoading" class="px-3">
        <n-skeleton v-for="i in 4" :key="i" :height="118" :sharp="false" size="medium" class="mt-4.5" />
      </div>

      <div
        v-show="!databaseListLoading && databaseList.length === 0"
        class="flex h-[533px] 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">{{ emptyDatabaseListText }}</p>
        </div>
      </div>
    </template>

    <template #footer></template>
  </CustomModal>

  <CreateDatabaseModal
    v-model:show-modal="showCreateDatabaseModal"
    :btn-loading="createDatabaseBtnLoading"
    @confirm="handleCreateDatabase"
  />
</template>
