<template>
  <v-dialog v-model="showQuickAdd" max-width="480" persistent>
    <v-card border>
      <v-card-title>快速添加服务器（仅 IP）</v-card-title>
      <v-card-text>
        <p class="text-body-2 text-medium-emphasis mb-3">
          将按顺序轮询凭据管理中的全部密码预设与 SSH 密钥预设尝试登录，首个成功即加入服务器列表。
        </p>
        <v-text-field
          v-model="quickAddForm.domain"
          label="IP 或域名"
          variant="outlined"
          density="compact"
          class="mb-2"
          placeholder="192.168.1.10"
          :rules="[v => !!v?.trim() || '必填']"
        />
        <v-text-field
          v-model.number="quickAddForm.port"
          label="SSH 端口"
          variant="outlined"
          density="compact"
          type="number"
          class="mb-2"
        />
        <v-text-field
          v-model="quickAddForm.name"
          label="显示名称（可选）"
          variant="outlined"
          density="compact"
          hint="留空则使用 IP"
          persistent-hint
        />
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn variant="text" :disabled="quickAddLoading" @click="showQuickAdd = false">取消</v-btn>
        <v-btn color="primary" variant="flat" :loading="quickAddLoading" @click="submitQuickAdd">开始轮询</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>

  <v-dialog v-model="showPollFailure" max-width="560">
    <v-card border>
      <v-card-title class="text-error">SSH 连接失败</v-card-title>
      <v-card-text>
        <p class="text-body-2 mb-3">已尝试全部凭据预设，均未登录成功。该服务器已加入「连接失败列表」，可稍后重试。</p>
        <v-list v-if="pollFailureErrors.length" density="compact" class="bg-grey-lighten-4 rounded">
          <v-list-item v-for="(err, i) in pollFailureErrors" :key="i">
            <v-list-item-title class="text-body-2">
              [{{ err.preset_type === 'password' ? '密码' : err.preset_type === 'system' ? '系统' : '密钥' }}]
              {{ err.preset_name }} ({{ err.username }})
            </v-list-item-title>
            <v-list-item-subtitle class="text-error">{{ err.error }}</v-list-item-subtitle>
          </v-list-item>
        </v-list>
        <p v-else class="text-medium-emphasis">{{ pollFailureMessage }}</p>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn color="primary" variant="flat" @click="showPollFailure = false">知道了</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { useServerQuickAdd, type UseServerQuickAddOptions } from '@/composables/servers/useServerQuickAdd'

const props = defineProps<UseServerQuickAddOptions>()

const {
  showQuickAdd,
  quickAddLoading,
  quickAddForm,
  showPollFailure,
  pollFailureErrors,
  pollFailureMessage,
  openQuickAdd,
  submitQuickAdd,
  showFailureDialog,
} = useServerQuickAdd({
  onSuccess: (res) => props.onSuccess?.(res),
  onPendingFailure: () => props.onPendingFailure?.(),
})

defineExpose({ open: openQuickAdd, showFailure: showFailureDialog })
</script>
