<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { targetApi } from '@/api/service-monitor'
import type { Target, CreateTargetRequest } from '@/types/service-monitor'

const targets = ref<Target[]>([])
const loading = ref(false)

// Dialog
const dialogVisible = ref(false)
const dialogTitle = ref('新增远程目标')
const editingId = ref<string | null>(null)
const saving = ref(false)
const testing = ref(false)
const testMessage = ref('')
const testSuccess = ref(false)

// Form
const form = ref<CreateTargetRequest>({
  name: '',
  host: '',
  port: 22,
  username: '',
  password: '',
})

// Load targets
async function loadTargets() {
  loading.value = true
  try {
    const res = await targetApi.getTargets()
    targets.value = res.targets || []
  } catch (e) {
    ElMessage.error('加载目标列表失败')
  } finally {
    loading.value = false
  }
}

// Open create dialog
function openCreate() {
  editingId.value = null
  dialogTitle.value = '新增远程目标'
  form.value = {
    name: '',
    host: '',
    port: 22,
    username: '',
    password: '',
  }
  testMessage.value = ''
  dialogVisible.value = true
}

// Open edit dialog
function openEdit(target: Target) {
  editingId.value = target.id
  dialogTitle.value = '编辑目标'
  form.value = {
    name: target.name,
    host: target.host,
    port: target.port,
    username: target.username,
    password: '', // 不回显密码
  }
  testMessage.value = ''
  dialogVisible.value = true
}

// Test connection
async function handleTestConnection() {
  if (!form.value.host || !form.value.username) {
    testMessage.value = '请填写主机和用户名'
    testSuccess.value = false
    return
  }

  testing.value = true
  testMessage.value = '测试中...'

  try {
    const res = await targetApi.testConnection({
      host: form.value.host,
      port: form.value.port,
      username: form.value.username,
      password: form.value.password,
    })

    if (res.success) {
      testMessage.value = '连接成功'
      testSuccess.value = true
    } else {
      testMessage.value = res.message || '连接失败'
      testSuccess.value = false
    }
  } catch (e: any) {
    testMessage.value = e.message || '请求失败'
    testSuccess.value = false
  } finally {
    testing.value = false
  }
}

// Save target
async function handleSave() {
  if (!form.value.name || !form.value.host || !form.value.username) {
    ElMessage.warning('请填写名称、主机和用户名')
    return
  }

  saving.value = true
  try {
    if (editingId.value) {
      await targetApi.updateTarget(editingId.value, form.value)
    } else {
      await targetApi.createTarget(form.value)
    }
    ElMessage.success('保存成功')
    dialogVisible.value = false
    loadTargets()
  } catch (e: any) {
    ElMessage.error(e.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// Delete target
async function handleDelete(target: Target) {
  try {
    await ElMessageBox.confirm(`确定删除目标「${target.name}」？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await targetApi.deleteTarget(target.id)
    ElMessage.success('删除成功')
    loadTargets()
  } catch {
    // 取消
  }
}

onMounted(loadTargets)
</script>

<template>
  <div class="page-targets">
    <div class="section-head">
      <h1 class="section-title">目标管理</h1>
      <el-button type="primary" @click="openCreate">
        + 新增远程目标
      </el-button>
    </div>

    <el-card v-loading="loading" class="table-card">
      <el-table :data="targets" style="width: 100%" row-key="id">
        <el-table-column prop="name" label="名称" min-width="150">
          <template #default="{ row }">
            <span class="name-cell">{{ (row as Target).name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="主机" min-width="180">
          <template #default="{ row }">
            {{ (row as Target).type === 'local' ? '本机' : `${(row as Target).host}:${(row as Target).port}` }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag
              :type="(row as Target).type === 'local' ? 'success' : 'primary'"
              size="small"
            >
              {{ (row as Target).type === 'local' ? '本机' : '远程' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="120">
          <template #default="{ row }">
            {{ (row as Target).username || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <template v-if="(row as Target).type === 'remote'">
              <el-button size="small" @click="openEdit(row as Target)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row as Target)">删除</el-button>
            </template>
            <template v-else>
              <el-button size="small" disabled>内置</el-button>
              <el-button size="small" type="danger" disabled>删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="460px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" label-position="top">
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="如：生产服务器" />
        </el-form-item>
        <el-form-item label="主机地址">
          <el-input v-model="form.host" placeholder="如：192.168.1.100" />
        </el-form-item>
        <el-form-item label="SSH 端口">
          <el-input-number v-model="form.port" :min="1" :max="65535" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="如：root" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="SSH 登录密码"
            show-password
          />
          <div class="form-hint">密码将加密存储</div>
        </el-form-item>
        <div class="test-section">
          <el-button :loading="testing" @click="handleTestConnection">
            测试连接
          </el-button>
          <span
            v-if="testMessage"
            class="test-msg"
            :class="{ success: testSuccess, error: !testSuccess }"
          >
            {{ testMessage }}
          </span>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.page-targets {
  padding: 0 0 40px;
}

.section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 700;
  color: $gray-900;
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.name-cell {
  font-weight: 600;
  color: $gray-900;
}

.form-hint {
  font-size: 12px;
  color: $gray-500;
  margin-top: 4px;
}

.test-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 14px;
}

.test-msg {
  font-size: 13px;

  &.success {
    color: $green;
  }

  &.error {
    color: $red;
  }
}

@media screen and (max-width: 768px) {
  .section-head {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .section-title {
    font-size: 16px;
  }
}
</style>