<template>
  <v-card
    id="unset-path-panel"
    elevation="0"
    rounded="lg"
    class="my-5 unset-path-panel"
    :class="{ 'unset-path-panel--highlight': highlight }"
    border
  >
    <v-card-title class="d-flex align-center flex-wrap ga-2">
      未设置路径服务器
      <v-chip v-if="total > 0" size="small" color="warning" variant="tonal" label>
        {{ total }}
      </v-chip>
      <v-spacer />
      <v-btn
        size="small"
        variant="tonal"
        :disabled="total === 0"
        :loading="selectAllLoading"
        @click="$emit('select-all-filtered')"
      >
        全选筛选结果 ({{ total }})
      </v-btn>
      <v-btn
        variant="text"
        size="small"
        prepend-icon="mdi-refresh"
        :loading="loading"
        @click="$emit('refresh')"
      >
        刷新
      </v-btn>
    </v-card-title>

    <ServerBatchActionBar
      :count="selectedCount"
      @batch-category="$emit('batch-category')"
      @health-check="$emit('health-check')"
      @detect-path="$emit('detect-path')"
      @install-agent="$emit('install-agent')"
      @upgrade-agent="$emit('upgrade-agent')"
      @uninstall-agent="$emit('uninstall-agent')"
      @batch-delete="$emit('batch-delete')"
      @clear="$emit('clear-selection')"
    />

    <v-data-table-server
      class="server-unset-path-table"
      :items="servers"
      :headers="headers"
      :items-length="total"
      :loading="loading"
      :page="page"
      :items-per-page="itemsPerPage"
      :items-per-page-options="itemsPerPageOptions"
      hover
      density="comfortable"
      item-value="id"
      show-select
      show-expand
      :model-value="selectedItems"
      :sort-by="sortBy"
      v-model:expanded="expandedModel"
      @update:model-value="$emit('update:selected-items', $event)"
      @update:sort-by="$emit('update:sort-by', $event)"
      @update:page="$emit('update:page', $event)"
      @update:items-per-page="$emit('update:items-per-page', $event)"
    >
      <template #item.data-table-expand />

      <template #item.status="{ item }">
        <v-chip :color="statusChipColor(item.status)" size="x-small" variant="tonal" label border="sm">
          {{ statusLabel(item.status) }}
        </v-chip>
      </template>

      <template #item.name="{ item }">
        <div
          class="d-flex align-center cursor-pointer text-primary"
          @click.stop="$emit('toggle-expand', item)"
        >
          <v-icon size="small" class="mr-1">
            {{ isExpandedId(item.id) ? 'mdi-chevron-down' : 'mdi-chevron-right' }}
          </v-icon>
          <span class="font-weight-medium">{{ item.name }}</span>
        </div>
      </template>

      <template #item.domain="{ item }">
        <span class="text-medium-emphasis">{{ item.domain }}:{{ item.port }}</span>
      </template>

      <template #item.category="{ item }">
        <v-chip v-if="item.category" color="primary" variant="tonal" size="small" label>
          {{ item.category }}
        </v-chip>
        <span v-else class="text-medium-emphasis">—</span>
      </template>

      <template #item.target_path="{ item }">
        <div v-if="editingPathId === item.id" class="d-flex align-center ga-1" @click.stop>
          <v-text-field
            :model-value="editingPathValue"
            density="compact"
            variant="outlined"
            hide-details
            placeholder="/www/wwwroot"
            style="max-width: 140px"
            @update:model-value="$emit('update:editing-path-value', $event)"
            @keyup.enter="$emit('save-path', item.id)"
            @keyup.esc="$emit('cancel-edit-path')"
          />
          <v-btn
            icon="mdi-check"
            size="x-small"
            variant="text"
            color="primary"
            :loading="savingPathId === item.id"
            @click="$emit('save-path', item.id)"
          />
          <v-btn icon="mdi-close" size="x-small" variant="text" @click="$emit('cancel-edit-path')" />
        </div>
        <div v-else class="d-flex align-center ga-1">
          <span
            class="text-caption text-medium-emphasis text-truncate d-inline-block"
            style="max-width: 140px"
            :title="item.target_path || '未配置'"
          >
            {{ item.target_path?.trim() || '—' }}
          </span>
          <v-btn
            icon="mdi-pencil"
            size="x-small"
            variant="text"
            density="compact"
            title="编辑目标路径"
            @click.stop="$emit('edit-path', item)"
          />
        </div>
      </template>

      <template #item.agent_version="{ item }">
        <span class="text-medium-emphasis">{{ item.agent_version || '—' }}</span>
      </template>

      <template #item.last_heartbeat="{ item }">
        <span class="text-caption text-medium-emphasis">{{ formatRelativeTime(item.last_heartbeat) }}</span>
      </template>

      <template #item.actions="{ item }">
        <div class="d-flex ga-1">
          <v-btn variant="text" size="x-small" color="primary" density="compact" @click.stop="$emit('terminal', item)">
            终端
          </v-btn>
          <v-btn variant="text" size="x-small" density="compact" @click.stop="$emit('files', item)">
            文件
          </v-btn>
          <v-btn variant="text" size="x-small" density="compact" @click.stop="$emit('detect-path-single', item)">
            检测路径
          </v-btn>
          <v-btn variant="text" size="x-small" density="compact" @click.stop="$emit('agent-diagnose', item)">
            诊断
          </v-btn>
          <v-btn variant="text" size="x-small" density="compact" @click.stop="$emit('edit', item)">
            编辑
          </v-btn>
          <v-btn variant="text" size="x-small" color="error" density="compact" @click.stop="$emit('delete', item)">
            删除
          </v-btn>
        </div>
      </template>

      <template #expanded-row="{ columns, item }">
        <tr>
          <td :colspan="columns.length" class="pa-0">
            <ServerInlineDetail
              :server="item"
              :active="isExpandedId(item.id)"
              @edit-path="$emit('edit-path', item)"
            />
          </td>
        </tr>
      </template>

      <template #no-data>
        <div class="text-center text-medium-emphasis py-6">暂无未设置路径的服务器</div>
      </template>
    </v-data-table-server>
  </v-card>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { ServerApiItem } from '@/types/api'
import type { TableSortItem } from '@/utils/serverTableSort'
import { statusChipColor, statusLabel, formatRelativeTime } from '@/utils/status'
import { normalizeServerIds } from '@/utils/serverSelection'
import ServerInlineDetail from '@/components/servers/ServerInlineDetail.vue'
import ServerBatchActionBar from '@/components/servers/ServerBatchActionBar.vue'

const props = defineProps<{
  highlight?: boolean
  servers: ServerApiItem[]
  loading: boolean
  total: number
  page: number
  itemsPerPage: number
  itemsPerPageOptions: ReadonlyArray<{ readonly value: number; readonly title: string }>
  sortBy: TableSortItem[]
  expandedIds: number[]
  selectedItems: Array<ServerApiItem | number>
  selectAllLoading: boolean
  editingPathId: number | null
  editingPathValue: string
  savingPathId: number | null
}>()

const emit = defineEmits<{
  refresh: []
  'update:sort-by': [sortBy: TableSortItem[]]
  'update:page': [page: number]
  'update:items-per-page': [n: number]
  'update:selected-items': [items: Array<ServerApiItem | number>]
  'update:expanded-ids': [ids: number[]]
  'update:editing-path-value': [value: string]
  'select-all-filtered': []
  'toggle-expand': [item: ServerApiItem]
  terminal: [item: ServerApiItem]
  files: [item: ServerApiItem]
  'detect-path-single': [item: ServerApiItem]
  'agent-diagnose': [item: ServerApiItem]
  edit: [item: ServerApiItem]
  delete: [item: ServerApiItem]
  'edit-path': [item: ServerApiItem]
  'save-path': [serverId: number]
  'cancel-edit-path': []
  'batch-category': []
  'health-check': []
  'detect-path': []
  'install-agent': []
  'upgrade-agent': []
  'uninstall-agent': []
  'batch-delete': []
  'clear-selection': []
}>()

const headers = [
  { title: '状态', key: 'status', width: 100 },
  { title: '名称', key: 'name' },
  { title: '地址', key: 'domain' },
  { title: '分类', key: 'category', width: 100 },
  { title: '目标路径', key: 'target_path', width: 200 },
  { title: 'Agent', key: 'agent_version', width: 100 },
  { title: '心跳', key: 'last_heartbeat', width: 120 },
  { title: '操作', key: 'actions', width: 260, align: 'end' as const, sortable: false },
]

const selectedCount = computed(() => normalizeServerIds(props.selectedItems).length)

const expandedModel = computed({
  get: () => props.expandedIds as unknown as readonly string[],
  set: (ids: readonly string[]) => {
    emit(
      'update:expanded-ids',
      ids.map((id) => Number(id)).filter((n) => !Number.isNaN(n)),
    )
  },
})

function isExpandedId(id: number): boolean {
  return props.expandedIds.includes(id)
}
</script>

<style scoped>
.server-unset-path-table :deep(.v-data-table__td--expand-column),
.server-unset-path-table :deep(.v-data-table-column--expand),
.server-unset-path-table :deep(th.v-data-table__th--expand) {
  display: none !important;
  width: 0 !important;
  padding: 0 !important;
}

.server-unset-path-table :deep(tr.v-data-table__expanded__row > td) {
  background: transparent !important;
  border-bottom: none;
}

.unset-path-panel--highlight {
  border-color: rgb(var(--v-theme-warning)) !important;
  box-shadow: 0 0 0 2px rgba(var(--v-theme-warning), 0.35) !important;
  scroll-margin-top: 80px;
}
</style>
