<template>
  <v-card elevation="0" border rounded="lg" class="mb-4">
    <v-card-title class="d-flex align-center flex-wrap ga-2">
      <v-checkbox
        :model-value="selectAll"
        label="全选"
        density="compact"
        hide-details
        class="mr-2"
        @update:model-value="$emit('toggle-all')"
      />
      <v-combobox
        :model-value="serverSearch"
        :items="searchHistory"
        prepend-inner-icon="mdi-magnify"
        label="搜索服务器..."
        density="compact"
        hide-details
        variant="outlined"
        rounded
        clearable
        :auto-select-first="false"
        placeholder="输入后回车，或从历史选择"
        style="max-width: 240px"
        @update:model-value="onSearchUpdate"
        @keydown.enter.prevent="$emit('search-commit')"
      />
      <v-btn
        icon="mdi-refresh"
        variant="text"
        size="small"
        :loading="serversLoading"
        title="刷新在线状态"
        @click="$emit('refresh')"
      />
      <v-spacer />
      <v-btn-toggle
        v-model="viewMode"
        mandatory
        density="compact"
        color="primary"
        variant="outlined"
        divided
      >
        <v-btn value="grid" size="small" icon="mdi-view-grid" title="卡片视图" />
        <v-btn value="list" size="small" icon="mdi-view-list" title="列表视图" />
      </v-btn-toggle>
    </v-card-title>
    <v-divider />
    <v-card-text class="pa-2">
      <template v-if="serversByCategory.length === 0">
        <div class="text-center text-medium-emphasis py-6">暂无服务器</div>
      </template>
      <template v-else>
        <div v-for="group in serversByCategory" :key="group.category" class="mb-4">
          <div class="d-flex align-center px-2 mb-2">
            <v-btn
              size="x-small"
              variant="text"
              :color="isCategoryAllSelected(group.category) ? 'primary' : 'default'"
              @click="$emit('toggle-category', group.category)"
            >
              <v-icon size="16" class="mr-1">
                {{ isCategoryAllSelected(group.category) ? 'mdi-checkbox-marked' : 'mdi-checkbox-blank-outline' }}
              </v-icon>
              {{ group.label }}
            </v-btn>
            <span class="text-caption text-medium-emphasis ml-1">
              ({{ group.servers.filter(s => selectedIds.has(s.id)).length }}/{{ group.servers.length }})
            </span>
          </div>

          <!-- 卡片视图 -->
          <v-row v-if="viewMode === 'grid'" dense>
            <v-col v-for="s in group.servers" :key="s.id" cols="6" sm="4" md="3" lg="2">
              <v-card
                :color="selectedIds.has(s.id) ? 'primary' : undefined"
                :variant="selectedIds.has(s.id) ? 'tonal' : 'outlined'"
                rounded="lg"
                class="pa-3 cursor-pointer push-server-card"
                @click="$emit('toggle-server', s.id)"
              >
                <div class="d-flex align-center ga-2 min-w-0">
                  <v-icon :color="serverOnlineColor(s.is_online)" size="12" class="flex-shrink-0">mdi-circle</v-icon>
                  <span
                    class="text-body-2 font-weight-medium push-server-card__name"
                    :title="serverLabelTitle(s)"
                  >{{ s.name }}</span>
                </div>
                <div
                  class="text-caption text-medium-emphasis push-server-card__line"
                  :title="s.domain || ''"
                >{{ s.domain }}</div>
                <div
                  class="text-caption text-medium-emphasis push-server-card__line"
                  :title="s.target_path || '未配置目标路径'"
                >
                  → {{ s.target_path?.trim() || '未配置' }}
                </div>
                <div v-if="pushStatus[s.id]" class="text-caption mt-1">
                  <v-chip
                    :color="pushStatusChipColor(pushStatus[s.id])"
                    size="x-small"
                    variant="tonal"
                    label
                    border="sm"
                  >
                    {{ pushStatus[s.id] }}
                  </v-chip>
                </div>
              </v-card>
            </v-col>
          </v-row>

          <!-- 列表视图 -->
          <v-table v-else density="compact" class="push-server-list rounded-lg border">
            <thead>
              <tr>
                <th class="push-server-list__col-check" />
                <th class="push-server-list__col-online" />
                <th>名称</th>
                <th>域名</th>
                <th>目标路径</th>
                <th class="push-server-list__col-status">状态</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="s in group.servers"
                :key="s.id"
                class="push-server-list__row cursor-pointer"
                :class="{ 'push-server-list__row--selected': selectedIds.has(s.id) }"
                @click="$emit('toggle-server', s.id)"
              >
                <td @click.stop>
                  <v-checkbox
                    :model-value="selectedIds.has(s.id)"
                    density="compact"
                    hide-details
                    @update:model-value="$emit('toggle-server', s.id)"
                  />
                </td>
                <td>
                  <v-icon :color="serverOnlineColor(s.is_online)" size="12">mdi-circle</v-icon>
                </td>
                <td class="push-server-list__name-cell">
                  <span :title="s.name">{{ s.name }}</span>
                </td>
                <td class="text-caption text-medium-emphasis push-server-list__ellipsis" :title="s.domain || ''">
                  {{ s.domain || '—' }}
                </td>
                <td class="text-caption text-medium-emphasis push-server-list__ellipsis" :title="s.target_path || '未配置'">
                  {{ s.target_path?.trim() || '未配置' }}
                </td>
                <td>
                  <v-chip
                    v-if="pushStatus[s.id]"
                    :color="pushStatusChipColor(pushStatus[s.id])"
                    size="x-small"
                    variant="tonal"
                    label
                    border="sm"
                  >
                    {{ pushStatus[s.id] }}
                  </v-chip>
                  <span v-else class="text-caption text-medium-emphasis">—</span>
                </td>
              </tr>
            </tbody>
          </v-table>
        </div>
      </template>
    </v-card-text>
  </v-card>
</template>

<script setup lang="ts">
import { pushStatusChipColor, serverOnlineColor } from '@/composables/push/labels'
import { usePushServerViewMode } from '@/composables/push/usePushServerViewMode'
import type { PushServerItem } from '@/composables/push/types'

defineProps<{
  selectAll: boolean
  serverSearch: string
  searchHistory: string[]
  serversLoading: boolean
  serversByCategory: { category: string; label: string; servers: PushServerItem[] }[]
  selectedIds: Set<number>
  pushStatus: Record<number, string>
  isCategoryAllSelected: (category: string) => boolean
}>()

const emit = defineEmits<{
  'update:serverSearch': [value: string | null]
  'search-commit': []
  'toggle-all': []
  refresh: []
  'toggle-category': [category: string]
  'toggle-server': [id: number]
}>()

const { viewMode } = usePushServerViewMode()

function onSearchUpdate(val: string | null) {
  emit('update:serverSearch', val)
}

function serverLabelTitle(s: PushServerItem): string {
  const parts = [s.name]
  if (s.domain?.trim()) parts.push(s.domain.trim())
  return parts.join('\n')
}
</script>

<style scoped>
.push-server-card__name {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  word-break: break-word;
  min-width: 0;
  flex: 1 1 auto;
  line-height: 1.25;
}
.push-server-card__line {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.push-server-list__col-check {
  width: 44px;
}
.push-server-list__col-online {
  width: 28px;
}
.push-server-list__col-status {
  width: 96px;
}
.push-server-list__row--selected {
  background: rgba(var(--v-theme-primary), 0.08);
}
.push-server-list__name-cell {
  max-width: 0;
  width: 32%;
  word-break: break-word;
}
.push-server-list__ellipsis {
  max-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.push-server-list :deep(th:nth-child(4)),
.push-server-list :deep(td:nth-child(4)) {
  width: 24%;
}
.push-server-list :deep(th:nth-child(5)),
.push-server-list :deep(td:nth-child(5)) {
  width: 28%;
}
</style>
