<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { fetchPagePerPage } from '@/utils/paginatedFetch'
import { useSnackbar } from '@/composables/useSnackbar'
import type { ServerApiItem } from '@/types/api'

const open = defineModel<boolean>({ required: true })
const snackbar = useSnackbar()

const props = defineProps<{
  slotIndex: number | null
  loading?: boolean
}>()

const emit = defineEmits<{
  pick: [serverId: number]
}>()

const search = ref('')
const listLoading = ref(false)
const servers = ref<ServerApiItem[]>([])
const selectedId = ref<number | null>(null)

const filteredServers = computed(() => {
  const q = search.value.toLowerCase().trim()
  if (!q) return servers.value
  return servers.value.filter(
    (s) =>
      s.name.toLowerCase().includes(q) ||
      (s.domain || '').toLowerCase().includes(q) ||
      (s.target_path || '').toLowerCase().includes(q) ||
      String(s.id).includes(q),
  )
})

watch(open, async (visible) => {
  if (!visible) {
    search.value = ''
    selectedId.value = null
    return
  }
  listLoading.value = true
  try {
    const res = await fetchPagePerPage<ServerApiItem>('/servers/', {}, 1, -1)
    servers.value = res.items
  } catch {
    servers.value = []
    snackbar('加载服务器列表失败', 'warning')
  } finally {
    listLoading.value = false
  }
})

function confirmPick() {
  if (selectedId.value == null) return
  emit('pick', selectedId.value)
}
</script>

<template>
  <v-dialog v-model="open" max-width="480" @keydown.enter.prevent="confirmPick">
    <v-card rounded="lg">
      <v-card-title>
        加入监测
        <span v-if="props.slotIndex != null" class="text-caption text-medium-emphasis ml-2">
          槽 {{ props.slotIndex + 1 }}
        </span>
      </v-card-title>
      <v-card-text>
        <v-autocomplete
          v-model="selectedId"
          v-model:search="search"
          :items="filteredServers"
          :loading="listLoading"
          item-title="name"
          item-value="id"
          label="搜索服务器"
          placeholder="名称 / 域名 / 路径 / ID"
          variant="outlined"
          density="compact"
          prepend-inner-icon="mdi-magnify"
          autofocus
          :custom-filter="() => true"
        >
          <template #item="{ props: itemProps, item }">
            <v-list-item v-bind="itemProps" :subtitle="item.domain">
              <template #prepend>
                <v-icon :color="item.is_online ? 'success' : 'grey'" size="8" class="mr-2">
                  mdi-circle
                </v-icon>
              </template>
            </v-list-item>
          </template>
        </v-autocomplete>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn variant="text" @click="open = false">取消</v-btn>
        <v-btn
          color="primary"
          variant="flat"
          :disabled="selectedId == null"
          :loading="loading"
          @click="confirmPick"
        >
          加入
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>
