<template>
  <div class="monthly-stats">
    <div class="page-header">
      <h2>월별 에러현황</h2>
      <div class="filter-section">
        <button class="nav-btn" @click="prevMonth">◀ 이전</button>
        <input type="month" v-model="selectedMonth" @change="loadStats" />
        <button class="nav-btn" @click="nextMonth">다음 ▶</button>
      </div>
    </div>

    <div v-if="loading" class="loading">
      <p>로딩중...</p>
    </div>

    <div v-else-if="stats.length === 0" class="no-data">
      <p>{{ formatMonth(selectedMonth) }}에 분석된 에러 데이터가 없습니다.</p>
    </div>

    <div v-else class="server-charts">
      <Card v-for="server in stats" :key="server.serverId" class="server-chart-card">
        <template #header>
          <div class="chart-header">
            <h3>🖥️ {{ server.serverName }}</h3>
            <span class="chart-subtitle">{{ formatMonth(selectedMonth) }} 일별 에러 ({{ getTotalCount(server) }}건)</span>
          </div>
        </template>
        <div class="chart-container">
          <Bar :data="getChartData(server)" :options="chartOptions" />
        </div>
      </Card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Card } from '@/components'
import { 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 loading = ref(false)
const stats = ref([])
const selectedMonth = ref(getCurrentMonth())

function getCurrentMonth() {
  const now = new Date()
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
}

function prevMonth() {
  const [year, month] = selectedMonth.value.split('-').map(Number)
  const date = new Date(year, month - 2, 1)
  selectedMonth.value = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
  loadStats()
}

function nextMonth() {
  const [year, month] = selectedMonth.value.split('-').map(Number)
  const date = new Date(year, month, 1)
  selectedMonth.value = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
  loadStats()
}

// Chart Options
const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'top',
    },
    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
    },
    y: {
      stacked: true,
      beginAtZero: true
    }
  }
}

// Chart Data 생성
const getChartData = (server) => {
  const labels = server.dailyStats.map(s => {
    const date = new Date(s.date)
    return `${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
      }
    ]
  }
}

// Load data
const loadStats = async () => {
  loading.value = true
  try {
    const [year, month] = selectedMonth.value.split('-').map(Number)
    stats.value = await scanApi.getMonthlyStatsByServer(year, month)
  } catch (e) {
    console.error('Failed to load stats:', e)
    stats.value = []
  } finally {
    loading.value = false
  }
}

// Utils
const formatMonth = (monthStr) => {
  const [year, month] = monthStr.split('-')
  return `${year}년 ${parseInt(month)}월`
}

const getTotalCount = (server) => {
  return server.dailyStats.reduce((sum, s) => sum + s.total, 0)
}

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

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

.page-header h2 {
  margin: 0;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-section input[type="month"] {
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}

.filter-section input[type="month"]:focus {
  outline: none;
  border-color: #3498db;
}

.nav-btn {
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.nav-btn:hover {
  background: #f0f0f0;
  border-color: #3498db;
}

.loading,
.no-data {
  text-align: center;
  padding: 60px;
  color: #666;
  background: white;
  border-radius: 8px;
}

.server-charts {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.server-chart-card {
  width: 100%;
}

.chart-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
}

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

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