<template>
  <v-dialog :model-value="modelValue" max-width="720" scrollable persistent @update:model-value="emit('update:modelValue', $event)">
    <v-card border>
      <v-card-title class="d-flex align-center">
        {{ isEditing ? '编辑服务器' : '添加服务器' }}
        <v-spacer />
        <v-btn icon="mdi-close" variant="text" size="small" :disabled="saving" @click="emit('update:modelValue', false)" />
      </v-card-title>

      <v-divider />

      <v-card-text class="pt-4">
        <v-progress-linear v-if="lookupsLoading" indeterminate color="primary" class="mb-3" />

        <div class="text-subtitle-2 text-medium-emphasis mb-2">基本信息</div>
        <v-row dense>
          <v-col cols="12" sm="6">
            <v-text-field
              v-model="form.name"
              label="名称"
              variant="outlined"
              density="compact"
              :rules="[required('服务器名称')]"
            />
          </v-col>
          <v-col cols="12" sm="6">
            <v-text-field
              v-model="form.domain"
              label="域名 / IP"
              variant="outlined"
              density="compact"
              placeholder="例：192.168.1.10"
              :rules="[required('域名或 IP')]"
            />
          </v-col>
          <v-col cols="6" sm="4">
            <v-text-field
              v-model.number="form.port"
              label="SSH 端口"
              type="number"
              variant="outlined"
              density="compact"
            />
          </v-col>
          <v-col cols="6" sm="8">
            <v-text-field
              v-model="form.username"
              label="SSH 用户名"
              variant="outlined"
              density="compact"
              placeholder="root"
              :rules="[required('SSH 用户名')]"
            />
          </v-col>
        </v-row>

        <v-divider class="my-4" />
        <div class="text-subtitle-2 text-medium-emphasis mb-2">认证方式</div>
        <v-btn-toggle v-model="form.auth_method" mandatory density="compact" variant="outlined" class="mb-3">
          <v-btn value="password" size="small">密码</v-btn>
          <v-btn value="key" size="small">SSH 密钥</v-btn>
        </v-btn-toggle>

        <template v-if="form.auth_method === 'password'">
          <v-select
            v-model="form.preset_id"
            :items="passwordPresets"
            item-title="display"
            item-value="id"
            label="密码预设（可选）"
            variant="outlined"
            density="compact"
            clearable
            class="mb-2"
            hint="选择后由服务端解密填入，无需再填密码框"
            persistent-hint
          />
          <v-text-field
            v-if="!form.preset_id"
            v-model="form.password"
            label="SSH 密码"
            variant="outlined"
            density="compact"
            type="password"
            :placeholder="isEditing && editHints.password_set ? '留空表示不修改' : '安装 Agent 需可 SSH'"
            :rules="passwordFieldRules"
          />
        </template>

        <template v-else>
          <v-select
            v-model="form.ssh_key_preset_id"
            :items="sshKeyPresets"
            item-title="display"
            item-value="id"
            label="SSH 密钥预设（可选）"
            variant="outlined"
            density="compact"
            clearable
            class="mb-2"
            hint="选择后由服务端解密私钥，无需再粘贴"
            persistent-hint
          />
          <v-text-field
            v-model="form.ssh_key_path"
            label="密钥路径（可选）"
            variant="outlined"
            density="compact"
            placeholder="~/.ssh/id_rsa"
            class="mb-2"
          />
          <v-textarea
            v-if="!form.ssh_key_preset_id"
            v-model="form.ssh_key_private"
            label="私钥 PEM"
            variant="outlined"
            density="compact"
            rows="4"
            auto-grow
            :placeholder="isEditing && editHints.ssh_key_private_set ? '留空表示不修改私钥' : '粘贴 -----BEGIN ... PRIVATE KEY-----'"
            :rules="sshKeyFieldRules"
          />
        </template>

        <v-divider class="my-4" />
        <div class="text-subtitle-2 text-medium-emphasis mb-2">部署</div>
        <v-text-field
          v-model="form.target_path"
          label="目标路径"
          variant="outlined"
          density="compact"
          placeholder="/www/wwwroot"
          hint="文件同步与推送的根目录，须为绝对路径"
          persistent-hint
          class="mb-2"
          :rules="[required('目标路径')]"
        />
        <v-combobox
          v-model="form.category"
          :items="categoryOptions"
          label="分类"
          variant="outlined"
          density="compact"
          clearable
          hint="可从已有分类选择或输入新分类"
          persistent-hint
        />

        <v-expansion-panels variant="accordion" class="mt-4">
          <v-expansion-panel title="高级选项">
            <v-expansion-panel-text>
              <v-select
                v-model="form.platform_id"
                :items="platforms"
                item-title="name"
                item-value="id"
                label="平台"
                variant="outlined"
                density="compact"
                clearable
                class="mb-2"
              />
              <v-select
                v-model="form.node_id"
                :items="nodes"
                item-title="name"
                item-value="id"
                label="节点"
                variant="outlined"
                density="compact"
                clearable
                class="mb-2"
              />
              <v-select
                v-model="form.files_elevation"
                :items="filesElevationItems"
                item-title="title"
                item-value="value"
                label="文件管理提权"
                variant="outlined"
                density="compact"
                hint="非 root 用户需目标机配置免密 sudo"
                persistent-hint
                class="mb-4"
              />
            </v-expansion-panel-text>
          </v-expansion-panel>
        </v-expansion-panels>
      </v-card-text>

      <v-divider />
      <v-card-actions class="pa-4">
        <v-spacer />
        <v-btn variant="text" :disabled="saving" @click="emit('update:modelValue', false)">取消</v-btn>
        <v-btn color="primary" variant="flat" :loading="saving" @click="emit('save')">保存</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { required } from '@/utils/validation'
import type { ServerFormModel, PresetOption } from '@/composables/servers/useServerFormDialog'
import type { FilesElevationMode } from '@/types/api'

const props = defineProps<{
  modelValue: boolean
  form: ServerFormModel
  isEditing: boolean
  saving: boolean
  lookupsLoading: boolean
  passwordPresets: PresetOption[]
  sshKeyPresets: PresetOption[]
  categoryOptions: string[]
  platforms: { id: number; name: string }[]
  nodes: { id: number; name: string }[]
  editHints: { password_set: boolean; ssh_key_private_set: boolean }
  filesElevationItems: { title: string; value: FilesElevationMode }[]
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  save: []
}>()

const passwordFieldRules = computed(() => {
  if (props.form.preset_id) return []
  if (props.isEditing) return []
  return [required('SSH 密码或选择密码预设')]
})

const sshKeyFieldRules = computed(() => {
  if (props.form.ssh_key_preset_id) return []
  if (props.isEditing) return []
  return [required('私钥或选择 SSH 密钥预设')]
})
</script>
