<template>
  <div class="daily-stats">
    <div class="page-header">
      <h2>일별 에러현황</h2>
      <div class="filter-section">
        <button class="nav-btn" @click="prevDay">◀ 이전</button>
        <input type="date" v-model="selectedDate" @change="loadStats" />
        <button class="nav-btn" @click="nextDay">다음 ▶</button>
      </div>
    </div>

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

    <div v-else-if="stats.length === 0" class="no-data">
      <p>{{ formatDate(selectedDate) }}에 분석된 에러 데이터가 없습니다.</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">{{ formatDate(selectedDate) }} 15분 단위 에러 ({{ getTotalCount(server) }}건)</span>
          </div>
        </template>
        <div class="chart-wrapper">
          <div class="chart-container">
            <Bar :data="getChartData(server)" :options="chartOptions" />
          </div>
        </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 selectedDate = ref(getCurrentDate())

function getCurrentDate() {
  const now = new Date()
  return now.toISOString().split('T')[0]
}

function prevDay() {
  const date = new Date(selectedDate.value)
  date.setDate(date.getDate() - 1)
  selectedDate.value = date.toISOString().split('T')[0]
  loadStats()
}

function nextDay() {
  const date = new Date(selectedDate.value)
  date.setDate(date.getDate() + 1)
  selectedDate.value = date.toISOString().split('T')[0]
  loadStats()
}

// Chart Options (10분 단위 144개 막대)
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: 0,
      font: {
        size: 9
      },
      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,
      ticks: {
        maxRotation: 0,
        autoSkip: true,
        maxTicksLimit: 24,
        callback: function(value, index) {
          const label = this.getLabelForValue(value)
          if (label && label.endsWith(':00')) {
            return label
          }
          return ''
        }
      },
      grid: {
        display: false
      }
    },
    y: {
      stacked: true,
      beginAtZero: true
    }
  },
  barPercentage: 0.8,
  categoryPercentage: 0.9
}

// Chart Data 생성
const getChartData = (server) => {
  const labels = server.timeStats.map(s => s.time)
  
  return {
    labels,
    datasets: [
      {
        label: 'CRITICAL',
        data: server.timeStats.map(s => s.critical),
        backgroundColor: '#9b59b6',
        borderWidth: 0
      },
      {
        label: 'ERROR',
        data: server.timeStats.map(s => s.error),
        backgroundColor: '#e74c3c',
        borderWidth: 0
      },
      {
        label: 'WARN',
        data: server.timeStats.map(s => s.warn),
        backgroundColor: '#f39c12',
        borderWidth: 0
      }
    ]
  }
}

// Load data (10분 단위)
const loadStats = async () => {
  loading.value = true
  try {
    stats.value = await scanApi.getTimeStatsByServer(selectedDate.value, 15)
  } catch (e) {
    console.error('Failed to load stats:', e)
    stats.value = []
  } finally {
    loading.value = false
  }
}

// Utils
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return `${date.getFullYear()}년 ${date.getMonth() + 1}월 ${date.getDate()}일`
}

const getTotalCount = (server) => {
  return server.timeStats.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="date"] {
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}

.filter-section input[type="date"]: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-wrapper {
  overflow-x: auto;
}

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