<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h2>대시보드</h2>
      <div class="header-actions">
        <Button 
          @click="scanAllServers" 
          :loading="scanningAll"
          :disabled="activeServers.length === 0"
        >
          전체 분석 실행
        </Button>
      </div>
    </div>

    <!-- 서버 목록 -->
    <div class="server-grid">
      <Card v-for="server in servers" :key="server.id" class="server-card">
        <template #header>
          <div class="server-header">
            <div class="server-title">
              <Badge :variant="server.active ? 'success' : 'default'" size="sm">
                {{ server.active ? '활성' : '비활성' }}
              </Badge>
              <h4>{{ server.name }}</h4>
            </div>
            <div class="server-actions">
              <Button 
                size="sm" 
                @click="scanServer(server)" 
                :loading="scanningServerId === server.id"
                :disabled="!server.active || scanningAll"
              >
                분석 실행
              </Button>
            </div>
          </div>
        </template>

        <div class="server-info">
          <div class="info-row">
            <span class="label">호스트</span>
            <span class="value">{{ server.host }}:{{ server.port }}</span>
          </div>
          <div class="info-row">
            <span class="label">마지막 분석</span>
            <span class="value">{{ formatDate(server.lastScanAt) }}</span>
          </div>
          <div class="info-row">
            <span class="label">마지막 에러</span>
            <span class="value" :class="{ 'has-error': server.lastErrorAt }">
              {{ formatDate(server.lastErrorAt) }}
            </span>
          </div>
        </div>

        <!-- 진행 상황 -->
        <div v-if="progressMap[server.id]" class="progress-section">
          <div class="progress-header">
            <span class="status-text">{{ getStatusText(progressMap[server.id]) }}</span>
            <Badge :variant="progressMap[server.id].status === 'RUNNING' ? 'warn' : 'success'">
              {{ progressMap[server.id].status }}
            </Badge>
          </div>
          <div class="progress-bar-container">
            <div 
              class="progress-bar" 
              :style="{ width: getProgressPercent(progressMap[server.id]) + '%' }"
            ></div>
          </div>
          <div class="progress-details">
            <span>파일: {{ progressMap[server.id].scannedFiles }} / {{ progressMap[server.id].totalFiles }}</span>
            <span>에러: {{ progressMap[server.id].errorsFound }}건</span>
          </div>
        </div>
      </Card>
    </div>

    <!-- 서버 없음 -->
    <Card v-if="servers.length === 0 && !loading" class="empty-card">
      <div class="empty-content">
        <p>등록된 서버가 없습니다.</p>
        <Button @click="$router.push('/servers')">서버 등록하기</Button>
      </div>
    </Card>

    <!-- 서버별 30일 에러 차트 -->
    <div v-if="dailyStats.length > 0" class="daily-charts">
      <h3>최근 30일 에러 추이</h3>
      <div class="chart-list">
        <Card v-for="server in dailyStats" :key="server.serverId" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>🖥️ {{ server.serverName }}</span>
              <span class="chart-total">총 {{ getTotalCount(server) }}건</span>
            </div>
          </template>
          <div class="chart-container">
            <Bar :data="getChartData(server)" :options="chartOptions" />
          </div>
        </Card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Card, Button, Badge } from '@/components'
import { serverApi, scanApi } from '@/api'
import { Bar } from 'vue-chartjs'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js'
import ChartDataLabels from 'chartjs-plugin-datalabels'

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, ChartDataLabels)

// State
const servers = ref([])
const dailyStats = ref([])
const loading = ref(false)
const scanningServerId = ref(null)
const scanningAll = ref(false)
const progressMap = ref({})

// Computed
const activeServers = computed(() => servers.value.filter(s => s.active))

// Chart options
const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      display: false
    },
    tooltip: {
      mode: 'index',
      intersect: false
    },
    datalabels: {
      display: (context) => {
        if (context.datasetIndex !== 2) return false
        const datasets = context.chart.data.datasets
        const index = context.dataIndex
        const total = datasets.reduce((sum, ds) => sum + (ds.data[index] || 0), 0)
        return total > 0
      },
      anchor: 'end',
      align: 'end',
      offset: 2,
      font: {
        size: 10,
        weight: 'bold'
      },
      color: '#666',
      formatter: (value, context) => {
        const datasets = context.chart.data.datasets
        const index = context.dataIndex
        return datasets.reduce((sum, ds) => sum + (ds.data[index] || 0), 0)
      }
    }
  },
  scales: {
    x: {
      stacked: true,
      grid: { display: false }
    },
    y: {
      stacked: true,
      beginAtZero: true,
      grid: { color: '#f0f0f0' }
    }
  }
}

// Chart data 생성
const getChartData = (server) => {
  const labels = server.dailyStats.map(s => {
    const date = new Date(s.date)
    return `${date.getMonth() + 1}/${date.getDate()}`
  })
  
  return {
    labels,
    datasets: [
      {
        label: 'CRITICAL',
        data: server.dailyStats.map(s => s.critical),
        backgroundColor: '#9b59b6',
        borderRadius: 2
      },
      {
        label: 'ERROR',
        data: server.dailyStats.map(s => s.error),
        backgroundColor: '#e74c3c',
        borderRadius: 2
      },
      {
        label: 'WARN',
        data: server.dailyStats.map(s => s.warn),
        backgroundColor: '#f39c12',
        borderRadius: 2
      }
    ]
  }
}

// 총 에러 수 계산
const getTotalCount = (server) => {
  return server.dailyStats.reduce((sum, s) => sum + s.total, 0)
}

// Load data
const loadServers = async () => {
  loading.value = true
  try {
    servers.value = await serverApi.getAll()
  } catch (e) {
    console.error('Failed to load servers:', e)
  } finally {
    loading.value = false
  }
}

const loadDailyStats = async () => {
  try {
    dailyStats.value = await scanApi.getDailyStatsByServer(30)
  } catch (e) {
    console.error('Failed to load daily stats:', e)
  }
}

// Scan single server
const scanServer = (server) => {
  scanningServerId.value = server.id
  progressMap.value[server.id] = {
    status: 'RUNNING',
    currentPath: '',
    currentFile: '',
    totalFiles: 0,
    scannedFiles: 0,
    errorsFound: 0
  }

  scanApi.startWithProgress(
    server.id,
    (progress) => {
      progressMap.value[server.id] = progress
    },
    (result) => {
      scanningServerId.value = null
      if (result.success) {
        progressMap.value[server.id] = { 
          ...progressMap.value[server.id], 
          status: 'SUCCESS',
          message: `완료: ${result.filesScanned}개 파일, ${result.errorsFound}개 에러`
        }
      } else {
        progressMap.value[server.id] = { 
          ...progressMap.value[server.id], 
          status: 'FAILED',
          message: result.error 
        }
      }
      loadServers()
      loadDailyStats()
      setTimeout(() => {
        delete progressMap.value[server.id]
      }, 5000)
    },
    (error) => {
      scanningServerId.value = null
      progressMap.value[server.id] = { 
        ...progressMap.value[server.id], 
        status: 'FAILED',
        message: error 
      }
    }
  )
}

// Scan all servers
const scanAllServers = () => {
  scanningAll.value = true
  
  scanApi.startAllWithProgress(
    (progress) => {
      progressMap.value[progress.serverId] = progress
    },
    (results) => {
      scanningAll.value = false
      loadServers()
      loadDailyStats()
      setTimeout(() => {
        progressMap.value = {}
      }, 5000)
    },
    (error) => {
      scanningAll.value = false
      alert('분석 실패: ' + error)
    }
  )
}

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

const getStatusText = (progress) => {
  if (progress.status === 'SUCCESS') return progress.message || '완료'
  if (progress.status === 'FAILED') return progress.message || '실패'
  if (progress.currentFile) return `분석중: ${progress.currentFile}`
  if (progress.currentPath) return `경로: ${progress.currentPath}`
  return '준비중...'
}

const getProgressPercent = (progress) => {
  if (progress.totalFiles === 0) return 0
  return Math.round((progress.scannedFiles / progress.totalFiles) * 100)
}

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

<style scoped>
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.dashboard-header h2 {
  margin: 0;
}

.server-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.server-card {
  transition: box-shadow 0.2s;
}

.server-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.server-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.server-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.server-title h4 {
  margin: 0;
  font-size: 16px;
}

.server-info {
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-row:last-child {
  border-bottom: none;
}

.info-row .label {
  color: #666;
  font-size: 13px;
}

.info-row .value {
  font-weight: 500;
}

.info-row .value.has-error {
  color: #e74c3c;
}

.progress-section {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-top: 12px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.status-text {
  font-size: 13px;
  color: #333;
}

.progress-bar-container {
  height: 8px;
  background: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-bar {
  height: 100%;
  background: #3498db;
  transition: width 0.3s;
}

.progress-details {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.empty-card {
  text-align: center;
}

.empty-content {
  padding: 40px 20px;
}

.empty-content p {
  margin-bottom: 16px;
  color: #666;
}

/* 차트 섹션 */
.daily-charts {
  margin-top: 32px;
}

.daily-charts h3 {
  margin-bottom: 16px;
  font-size: 18px;
}

.chart-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.chart-card {
  width: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-total {
  font-size: 13px;
  color: #888;
}

.chart-container {
  height: 200px;
  padding: 8px 0;
}
</style>
