<template>
  <a-modal :visible="props.visible" :title="editingId ? '编辑连接' : '添加服务器'" unmount-on-close @cancel="emit('update:visible', false)" @before-ok="handleOk" :ok-loading="submitting">
    <div style="display: flex; flex-direction: column; gap: 10px; max-width: 420px">
      <!-- 连接类型 -->
      <div style="display: flex; align-items: center; gap: 8px">
        <label style="font-size: 13px; width: 36px; flex-shrink: 0">类型</label>
        <a-radio-group v-model="form.type" type="button" size="small">
          <a-radio value="sftp">SFTP</a-radio>
          <a-radio value="remote">HTTP Agent</a-radio>
        </a-radio-group>
      </div>

      <!-- 名称 -->
      <div style="display: flex; align-items: center; gap: 8px">
        <label style="font-size: 13px; width: 36px; flex-shrink: 0">名称</label>
        <a-input v-model="form.name" placeholder="如：生产服务器" style="flex: 1" />
      </div>

      <!-- 地址 -->
      <div style="display: flex; align-items: center; gap: 8px">
        <label style="font-size: 13px; width: 36px; flex-shrink: 0">地址</label>
        <a-input v-model="form.host" :placeholder="form.type === 'sftp' ? '192.168.1.100' : '192.168.1.100'" style="flex: 1" />
        <a-input-number v-model="form.port" :min="1" :max="65535" :placeholder="form.type === 'sftp' ? '22' : '9876'" style="width: 90px" hide-button />
      </div>

      <!-- SFTP 认证字段 -->
      <template v-if="form.type === 'sftp'">
        <div style="display: flex; align-items: center; gap: 8px">
          <label style="font-size: 13px; width: 36px; flex-shrink: 0">用户</label>
          <a-input v-model="form.username" placeholder="root" style="flex: 1" />
        </div>

        <div style="display: flex; align-items: center; gap: 8px">
          <label style="font-size: 13px; width: 36px; flex-shrink: 0">密码</label>
          <a-input v-model="form.password" type="password" placeholder="登录密码（或使用密钥）" allow-clear style="flex: 1" />
        </div>
        <div v-if="editingId && form.type === 'sftp' && !form.password" style="font-size: 11px; color: var(--color-text-3); margin-left: 44px">
          未填写密码，将使用密钥认证（若密钥也为空则连接将失败）
        </div>

        <!-- 暂时隐藏密钥栏
        <div style="display: flex; align-items: center; gap: 8px">
          <label style="font-size: 13px; width: 36px; flex-shrink: 0">密钥</label>
          <a-input v-model="form.keyPath" placeholder="私钥文件路径（可选，优先于密码）" style="flex: 1" />
          <a-button size="small" @click="selectKeyFile">浏览</a-button>
        </div>

        <div style="font-size: 11px; color: var(--color-text-3)">
          支持密码或私钥文件认证，两者填一即可
        </div>
        -->
      </template>

      <!-- HTTP Agent Token 字段 -->
      <template v-if="form.type === 'remote'">
        <div style="display: flex; align-items: center; gap: 8px">
          <label style="font-size: 13px; width: 36px; flex-shrink: 0">Token</label>
          <div style="flex: 1">
            <a-input v-model="form.token" type="password" placeholder="留空则不认证" allow-clear />
            <div style="font-size: 11px; color: var(--color-text-3); margin-top: 2px">API 认证令牌（与服务器配置一致）</div>
          </div>
        </div>
      </template>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { Dialogs } from '@wailsio/runtime'
import { GetEnvVars } from '@bindings/u-desk/app'
import { connectionManager } from '@/api/connection-manager'
import type { ConnectionType } from '@/api/connection-manager'

const props = defineProps<{ visible: boolean }>()
const emit = defineEmits<{ (e: 'update:visible', val: boolean): void; (e: 'close'): void }>()

const editingId = ref<string | null>(null)
const submitting = ref(false)
let cachedSshDir = ''

onMounted(async () => {
  const env = await GetEnvVars()
  cachedSshDir = `${env.USERPROFILE || env.HOME || ''}\\.ssh`
})

const form = reactive({
  name: '',
  host: '',
  port: 22,
  token: '',
  type: 'sftp' as ConnectionType,
  username: 'root',
  password: '',
  keyPath: '',
})

watch(() => props.visible, (val) => {
  if (!val) return
  editingId.value = null
  Object.assign(form, {
    name: '', host: '', port: 22, token: '',
    type: 'sftp' as ConnectionType,
    username: 'root', password: '', keyPath: '',
  })
})

watch(() => form.type, (t) => {
  form.port = t === 'sftp' ? 22 : 9876
})

async function handleOk(): Promise<boolean> {
  if (!form.name?.trim()) { Message.warning('请输入名称'); return false }
  if (!form.host?.trim()) { Message.warning('请输入地址'); return false }

  submitting.value = true
  try {
    if (editingId.value) {
      await connectionManager.updateProfile(editingId.value, { ...form })
      Message.success('已更新')
    } else {
      await connectionManager.addProfile({ ...form, type: form.type })
      Message.success('已添加')
    }
    emit('update:visible', false)
    return true
  } catch (err) {
    Message.error(err instanceof Error ? err.message : '保存失败')
    return false
  } finally {
    submitting.value = false
  }
}

async function selectKeyFile() {
  const path = await Dialogs.OpenFile({
    Title: '选择私钥文件',
    Directory: cachedSshDir,
    CanChooseFiles: true,
    CanChooseDirectories: false,
  })
  if (path) form.keyPath = path
}

function editProfile(id: string) {
  const profile = connectionManager.profiles.find(p => p.id === id)
  if (!profile) return
  editingId.value = id
  Object.assign(form, {
    name: profile.name,
    host: profile.host,
    port: profile.port,
    token: profile.token || '',
    type: profile.type || 'remote',
    username: profile.username || 'root',
    password: profile.password || '',
    keyPath: profile.keyPath || '',
  })
}

defineExpose({ editProfile })
</script>
