<template>
  <div class="server-manage">
    <Card>
      <template #header>
        <div class="card-header-content">
          <h3>서버 관리</h3>
          <Button @click="openAddModal">+ 서버 추가</Button>
        </div>
      </template>

      <DataTable
        :columns="columns"
        :data="servers"
        :loading="loading"
        empty-text="등록된 서버가 없습니다."
      >
        <template #active="{ value }">
          <Badge :variant="value ? 'success' : 'default'">
            {{ value ? '활성' : '비활성' }}
          </Badge>
        </template>
        <template #authType="{ value }">
          {{ value === 'PASSWORD' ? '비밀번호' : '키 파일' }}
        </template>
        <template #lastScanAt="{ value }">
          {{ value ? formatDate(value) : '-' }}
        </template>
        <template #actions="{ row }">
          <div class="action-buttons">
            <Button size="sm" variant="success" @click="testConnection(row)" :loading="testingId === row.id">테스트</Button>
            <Button size="sm" variant="secondary" @click="openLogPathModal(row)">경로</Button>
            <Button size="sm" @click="openEditModal(row)">수정</Button>
            <Button size="sm" variant="danger" @click="confirmDelete(row)">삭제</Button>
          </div>
        </template>
      </DataTable>
    </Card>

    <!-- 서버 추가/수정 모달 -->
    <Modal v-model="showServerModal" :title="isEdit ? '서버 수정' : '서버 추가'" width="500px">
      <form @submit.prevent="saveServer">
        <FormInput
          v-model="form.name"
          label="서버명"
          placeholder="예: 운영서버1"
          required
        />
        <FormInput
          v-model="form.host"
          label="호스트"
          placeholder="예: 192.168.1.100"
          required
        />
        <FormInput
          v-model="form.port"
          label="포트"
          type="number"
          placeholder="22"
        />
        <FormInput
          v-model="form.username"
          label="사용자명"
          placeholder="예: root"
          required
        />
        <FormInput
          v-model="form.authType"
          label="인증 방식"
          type="select"
          :options="authTypeOptions"
          required
        />
        <FormInput
          v-if="form.authType === 'PASSWORD'"
          v-model="form.password"
          label="비밀번호"
          type="password"
          :placeholder="isEdit ? '변경 시에만 입력' : '비밀번호 입력'"
          :required="!isEdit"
        />
        <FormInput
          v-if="form.authType === 'KEY_FILE'"
          v-model="form.keyFilePath"
          label="키 파일 경로"
          placeholder="예: C:\Users\user\.ssh\id_rsa"
          required
        />
        <FormInput
          v-if="form.authType === 'KEY_FILE'"
          v-model="form.passphrase"
          label="Passphrase"
          type="password"
          :placeholder="isEdit ? '변경 시에만 입력' : 'Passphrase (없으면 비워두세요)'"
        />
        <div class="form-group">
          <label>
            <input type="checkbox" v-model="form.active" />
            활성화
          </label>
        </div>
      </form>
      <template #footer>
        <Button variant="secondary" @click="showServerModal = false">취소</Button>
        <Button @click="saveServer" :loading="saving">저장</Button>
      </template>
    </Modal>

    <!-- 로그 경로 관리 모달 -->
    <Modal v-model="showLogPathModal" :title="`로그 경로 관리 - ${selectedServer?.name || ''}`" width="700px">
      <div class="log-path-section">
        <div class="log-path-form">
          <h4>경로 추가</h4>
          <div class="log-path-inputs">
            <FormInput
              v-model="logPathForm.path"
              label="경로"
              placeholder="예: /var/log/tomcat/"
            />
            <FormInput
              v-model="logPathForm.filePattern"
              label="파일 패턴"
              placeholder="예: *.log, catalina.*.log"
            />
            <FormInput
              v-model="logPathForm.description"
              label="설명"
              placeholder="예: Tomcat 로그"
            />
          </div>
          <Button size="sm" @click="addLogPath" :disabled="!logPathForm.path || !logPathForm.filePattern">
            추가
          </Button>
        </div>

        <div class="log-path-list">
          <h4>등록된 경로</h4>
          <table v-if="logPaths.length > 0">
            <thead>
              <tr>
                <th>경로</th>
                <th>파일 패턴</th>
                <th>설명</th>
                <th>활성</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="lp in logPaths" :key="lp.id">
                <td>{{ lp.path }}</td>
                <td>{{ lp.filePattern }}</td>
                <td>{{ lp.description || '-' }}</td>
                <td>
                  <Badge :variant="lp.active ? 'success' : 'default'">
                    {{ lp.active ? 'Y' : 'N' }}
                  </Badge>
                </td>
                <td>
                  <Button size="sm" variant="danger" @click="deleteLogPath(lp.id)">삭제</Button>
                </td>
              </tr>
            </tbody>
          </table>
          <p v-else class="empty-text">등록된 경로가 없습니다.</p>
        </div>
      </div>
      <template #footer>
        <Button variant="secondary" @click="showLogPathModal = false">닫기</Button>
      </template>
    </Modal>

    <!-- 삭제 확인 모달 -->
    <Modal v-model="showDeleteModal" title="서버 삭제" width="400px">
      <p>정말로 <strong>{{ deleteTarget?.name }}</strong> 서버를 삭제하시겠습니까?</p>
      <p class="warning-text">관련된 모든 로그 경로와 에러 이력도 함께 삭제됩니다.</p>
      <template #footer>
        <Button variant="secondary" @click="showDeleteModal = false">취소</Button>
        <Button variant="danger" @click="deleteServer" :loading="deleting">삭제</Button>
      </template>
    </Modal>

    <!-- 연결 테스트 결과 모달 -->
    <Modal v-model="showTestResultModal" title="연결 테스트 결과" width="450px">
      <div class="test-result" :class="{ success: testResult?.success, fail: !testResult?.success }">
        <div v-if="testResult?.success">
          <p>✅ {{ testResult.message }}</p>
        </div>
        <div v-else>
          <p>❌ {{ testResult?.error }}</p>
        </div>
      </div>
      <template #footer>
        <Button variant="secondary" @click="showTestResultModal = false">닫기</Button>
      </template>
    </Modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { DataTable, Modal, FormInput, Button, Badge, Card } from '@/components'
import { serverApi, logPathApi } from '@/api'

const columns = [
  { key: 'name', label: '서버명', width: '150px' },
  { key: 'host', label: '호스트' },
  { key: 'port', label: '포트', width: '80px' },
  { key: 'authType', label: '인증방식', width: '100px' },
  { key: 'active', label: '상태', width: '80px' },
  { key: 'lastScanAt', label: '마지막 분석', width: '150px' }
]

const authTypeOptions = [
  { value: 'PASSWORD', label: '비밀번호' },
  { value: 'KEY_FILE', label: '키 파일' }
]

// State
const servers = ref([])
const loading = ref(false)
const saving = ref(false)
const deleting = ref(false)

// Server Modal
const showServerModal = ref(false)
const isEdit = ref(false)
const editId = ref(null)
const form = ref({
  name: '',
  host: '',
  port: 22,
  username: '',
  authType: 'PASSWORD',
  password: '',
  keyFilePath: '',
  passphrase: '',
  active: true
})

// LogPath Modal
const showLogPathModal = ref(false)
const selectedServer = ref(null)
const logPaths = ref([])
const logPathForm = ref({
  path: '',
  filePattern: '',
  description: ''
})

// Delete Modal
const showDeleteModal = ref(false)
const deleteTarget = ref(null)

// Test Connection
const testingId = ref(null)
const showTestResultModal = ref(false)
const testResult = ref(null)

// Load servers
const loadServers = async () => {
  loading.value = true
  try {
    servers.value = await serverApi.getAll()
  } catch (e) {
    console.error('Failed to load servers:', e)
    alert('서버 목록을 불러오는데 실패했습니다.')
  } finally {
    loading.value = false
  }
}

// Open Add Modal
const openAddModal = () => {
  isEdit.value = false
  editId.value = null
  form.value = {
    name: '',
    host: '',
    port: 22,
    username: '',
    authType: 'PASSWORD',
    password: '',
    keyFilePath: '',
    passphrase: '',
    active: true
  }
  showServerModal.value = true
}

// Open Edit Modal
const openEditModal = (server) => {
  isEdit.value = true
  editId.value = server.id
  form.value = {
    name: server.name,
    host: server.host,
    port: server.port,
    username: server.username,
    authType: server.authType,
    password: '',
    keyFilePath: server.keyFilePath || '',
    passphrase: '',
    active: server.active
  }
  showServerModal.value = true
}

// Save Server
const saveServer = async () => {
  if (!form.value.name || !form.value.host || !form.value.username) {
    alert('필수 항목을 입력해주세요.')
    return
  }

  saving.value = true
  try {
    if (isEdit.value) {
      await serverApi.update(editId.value, form.value)
    } else {
      await serverApi.create(form.value)
    }
    showServerModal.value = false
    await loadServers()
  } catch (e) {
    console.error('Failed to save server:', e)
    alert('저장에 실패했습니다.')
  } finally {
    saving.value = false
  }
}

// Delete
const confirmDelete = (server) => {
  deleteTarget.value = server
  showDeleteModal.value = true
}

const deleteServer = async () => {
  deleting.value = true
  try {
    await serverApi.delete(deleteTarget.value.id)
    showDeleteModal.value = false
    await loadServers()
  } catch (e) {
    console.error('Failed to delete server:', e)
    alert('삭제에 실패했습니다.')
  } finally {
    deleting.value = false
  }
}

// Test Connection
const testConnection = async (server) => {
  testingId.value = server.id
  try {
    testResult.value = await serverApi.testConnection(server.id)
    showTestResultModal.value = true
  } catch (e) {
    console.error('Failed to test connection:', e)
    testResult.value = { success: false, error: '연결 테스트 실패: ' + e.message }
    showTestResultModal.value = true
  } finally {
    testingId.value = null
  }
}

// Log Path Modal
const openLogPathModal = async (server) => {
  selectedServer.value = server
  logPathForm.value = { path: '', filePattern: '', description: '' }
  try {
    logPaths.value = await logPathApi.getByServerId(server.id)
  } catch (e) {
    console.error('Failed to load log paths:', e)
    logPaths.value = []
  }
  showLogPathModal.value = true
}

const addLogPath = async () => {
  try {
    await logPathApi.create({
      serverId: selectedServer.value.id,
      path: logPathForm.value.path,
      filePattern: logPathForm.value.filePattern,
      description: logPathForm.value.description,
      active: true
    })
    logPaths.value = await logPathApi.getByServerId(selectedServer.value.id)
    logPathForm.value = { path: '', filePattern: '', description: '' }
  } catch (e) {
    console.error('Failed to add log path:', e)
    alert('경로 추가에 실패했습니다.')
  }
}

const deleteLogPath = async (id) => {
  if (!confirm('이 경로를 삭제하시겠습니까?')) return
  try {
    await logPathApi.delete(id)
    logPaths.value = await logPathApi.getByServerId(selectedServer.value.id)
  } catch (e) {
    console.error('Failed to delete log path:', e)
    alert('경로 삭제에 실패했습니다.')
  }
}

// Utils
const formatDate = (dateStr) => {
  return new Date(dateStr).toLocaleString('ko-KR')
}

onMounted(() => {
  loadServers()
})
</script>

<style scoped>
.card-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header-content h3 {
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.log-path-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #333;
}

.log-path-form {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.log-path-inputs {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 12px;
  margin-bottom: 12px;
}

.log-path-list table {
  width: 100%;
  border-collapse: collapse;
}

.log-path-list th,
.log-path-list td {
  padding: 10px 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.log-path-list th {
  background: #f8f9fa;
  font-weight: 600;
  font-size: 13px;
}

.empty-text {
  color: #6c757d;
  text-align: center;
  padding: 20px;
}

.warning-text {
  color: #e74c3c;
  font-size: 14px;
}

.test-result {
  padding: 16px;
  border-radius: 8px;
}

.test-result.success {
  background: #d4edda;
  border: 1px solid #c3e6cb;
}

.test-result.fail {
  background: #f8d7da;
  border: 1px solid #f5c6cb;
}

.test-result p {
  margin: 0;
}
</style>
