<template>
  <div class="analytics-page">
    <div class="page-header flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-[#d4b383]">数据分析</h1>
      <div class="date-filter flex gap-2">
        <div class="quick-select flex bg-white/5 rounded-lg p-1 border border-white/10">
          <button 
            v-for="range in dateRanges" 
            :key="range.value"
            @click="selectRange(range.value)"
            class="px-3 py-1 text-sm rounded transition-colors"
            :class="selectedRange === range.value ? 'bg-[#d4b383] text-black' : 'text-white/60 hover:text-white'"
          >
            {{ range.label }}
          </button>
        </div>
        <div class="custom-date flex gap-2 items-center">
           <!-- 使用datetime-local以支持精确到分钟，虽然这里主要用日期，但预留接口 -->
           <input type="datetime-local" v-model="startDateTime" class="bg-white/5 border border-white/10 rounded px-2 py-1 text-white text-sm outline-none focus:border-[#d4b383]" @change="validateDates">
           <span class="text-white/40">-</span>
           <input type="datetime-local" v-model="endDateTime" class="bg-white/5 border border-white/10 rounded px-2 py-1 text-white text-sm outline-none focus:border-[#d4b383]" @change="validateDates">
           
           <button @click="clearDates" class="px-2 py-1 text-white/40 hover:text-white text-sm" title="清空">✕</button>
           <button @click="handleSearch" class="px-3 py-1 bg-[#d4b383]/20 text-[#d4b383] border border-[#d4b383]/50 rounded text-sm hover:bg-[#d4b383]/30 transition-colors" :disabled="loading">
             {{ loading ? '加载中...' : '查询' }}
           </button>
        </div>
      </div>
    </div>

    <div v-if="dateError" class="mb-4 p-3 bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg text-sm">
      {{ dateError }}
    </div>

    <!-- Charts Row 1 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- New Posts Trend -->
      <div class="chart-card relative">
        <h3 class="chart-title">新增博文趋势</h3>
        <div class="h-80" v-if="!loading && hasData(stats.postsTrend)">
          <v-chart class="chart" :option="postsTrendOption" autoresize />
        </div>
        <div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
          加载中...
        </div>
        <div v-else class="h-80 flex items-center justify-center text-white/20">
          暂无数据
        </div>
      </div>

      <!-- UV Trend -->
      <div class="chart-card relative">
        <h3 class="chart-title">访客趋势 (UV)</h3>
        <div class="h-80" v-if="!loading && hasData(stats.uvTrend)">
          <v-chart class="chart" :option="uvTrendOption" autoresize />
        </div>
        <div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
          加载中...
        </div>
        <div v-else class="h-80 flex items-center justify-center text-white/20">
          暂无数据
        </div>
      </div>
    </div>

    <!-- Charts Row 2 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- User Regions -->
      <div class="chart-card relative">
        <h3 class="chart-title">用户地域分布</h3>
        <div class="h-80" v-if="!loading && hasData(stats.userRegions)">
          <v-chart class="chart" :option="regionOption" autoresize />
        </div>
        <div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
          加载中...
        </div>
        <div v-else class="h-80 flex items-center justify-center text-white/20">
          暂无数据
        </div>
      </div>

      <!-- Top Posts -->
      <div class="chart-card relative">
        <h3 class="chart-title">热门文章 Top 5</h3>
        <div class="h-80" v-if="!loading && hasData(stats.topPosts)">
          <v-chart class="chart" :option="topPostsOption" autoresize />
        </div>
        <div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
          加载中...
        </div>
        <div v-else class="h-80 flex items-center justify-center text-white/20">
          暂无数据
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { getDashboardStats } from '../../../services/api'
import { useToast } from '../../../composables/useToast'

use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

const toast = useToast()
const stats = ref<any>({})
const loading = ref(false)
const selectedRange = ref('7d')
const startDateTime = ref('')
const endDateTime = ref('')
const dateError = ref('')

const dateRanges = [
  { label: '今日', value: 'today' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '近7天', value: '7d' },
  { label: '近30天', value: '30d' },
  { label: '近一年', value: '1y' }
]

const hasData = (data: any[]) => {
  return data && data.length > 0
}

const selectRange = (value: string) => {
  selectedRange.value = value
  const end = new Date()
  const start = new Date()
  
  if (value === 'today') {
    start.setHours(0, 0, 0, 0)
    end.setHours(23, 59, 59, 999)
  } else if (value === 'week') {
    const day = start.getDay() || 7 // Get current day number, make Sunday 7
    if (day !== 1) start.setHours(-24 * (day - 1)) // Set to Monday
    else start.setHours(0,0,0,0)
  } else if (value === 'month') {
    start.setDate(1)
    start.setHours(0,0,0,0)
  } else if (value === '7d') {
    start.setDate(end.getDate() - 6)
  } else if (value === '30d') {
    start.setDate(end.getDate() - 29)
  } else if (value === '1y') {
    start.setFullYear(end.getFullYear() - 1)
  }
  
  startDateTime.value = formatDateTime(start)
  endDateTime.value = formatDateTime(end)
  dateError.value = ''
  loadData()
}

const formatDateTime = (date: Date) => {
  // YYYY-MM-DDTHH:mm
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day}T${hours}:${minutes}`
}

const validateDates = () => {
  if (startDateTime.value && endDateTime.value) {
    if (new Date(startDateTime.value) > new Date(endDateTime.value)) {
      dateError.value = '开始时间不能晚于结束时间'
      return false
    }
  }
  dateError.value = ''
  return true
}

const clearDates = () => {
  startDateTime.value = ''
  endDateTime.value = ''
  selectedRange.value = ''
  loadData()
}

const handleSearch = () => {
  if (validateDates()) {
    selectedRange.value = '' // Clear preset selection when manual search
    loadData()
  }
}

// Chart Options
const postsTrendOption = computed(() => ({
  tooltip: { 
    trigger: 'axis',
    backgroundColor: 'rgba(0,0,0,0.8)',
    borderColor: '#333',
    textStyle: { color: '#fff' },
    formatter: function(params: any) {
      let result = params[0].name + '<br/>';
      params.forEach((item: any) => {
        result += item.marker + item.seriesName + ': ' + item.value + ' 篇<br/>';
        // if (data.yoy) result += '同比: ' + data.yoy + '%<br/>';
        // if (data.mom) result += '环比: ' + data.mom + '%<br/>';
      });
      return result;
    }
  },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: {
    type: 'category',
    data: stats.value.postsTrend?.map((i: any) => i.date) || [],
    axisLabel: { color: '#ccc' }
  },
  yAxis: {
    type: 'value',
    axisLabel: { color: '#ccc' },
    splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
  },
  series: [{
    name: '新增文章',
    data: stats.value.postsTrend?.map((i: any) => i.value) || [],
    type: 'line',
    smooth: true,
    itemStyle: { color: '#3b82f6' },
    areaStyle: { color: 'rgba(59, 130, 246, 0.1)' }
  }]
}))

const uvTrendOption = computed(() => ({
  tooltip: { 
    trigger: 'axis',
    backgroundColor: 'rgba(0,0,0,0.8)',
    borderColor: '#333',
    textStyle: { color: '#fff' }
  },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: {
    type: 'category',
    data: stats.value.uvTrend?.map((i: any) => i.date) || [],
    axisLabel: { color: '#ccc' }
  },
  yAxis: {
    type: 'value',
    axisLabel: { color: '#ccc' },
    splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
  },
  series: [{
    name: '访客数 (UV)',
    data: stats.value.uvTrend?.map((i: any) => i.value) || [],
    type: 'bar',
    itemStyle: { color: '#10b981' },
    barWidth: '40%'
  }]
}))

const regionOption = computed(() => ({
  tooltip: { 
    trigger: 'item',
    backgroundColor: 'rgba(0,0,0,0.8)',
    borderColor: '#333',
    textStyle: { color: '#fff' },
    formatter: '{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    textStyle: { color: '#ccc' }
  },
  series: [
    {
      name: '访问来源',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#050505',
        borderWidth: 2
      },
      label: { show: false, position: 'center' },
      emphasis: {
        label: { show: true, fontSize: 20, fontWeight: 'bold', color: '#fff' }
      },
      labelLine: { show: false },
      data: stats.value.userRegions?.map((i: any) => ({ value: i.Count, name: i.Region })) || []
    }
  ]
}))

const topPostsOption = computed(() => ({
  tooltip: { 
    trigger: 'axis', 
    axisPointer: { type: 'shadow' },
    backgroundColor: 'rgba(0,0,0,0.8)',
    borderColor: '#333',
    textStyle: { color: '#fff' }
  },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: {
    type: 'value',
    axisLabel: { color: '#ccc' },
    splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
  },
  yAxis: {
    type: 'category',
    inverse: true,
    data: stats.value.topPosts?.map((i: any) => i.title.length > 10 ? i.title.substring(0, 10) + '...' : i.title) || [],
    axisLabel: { color: '#ccc' }
  },
  series: [
    {
      name: '阅读量',
      type: 'bar',
      data: stats.value.topPosts?.map((i: any) => i.count) || [],
      itemStyle: { color: '#d4b383' }
    }
  ]
}))

const loadData = async () => {
  loading.value = true
  try {
    // Convert datetime-local format to API expected format if needed
    // Assuming API accepts YYYY-MM-DD or YYYY-MM-DD HH:mm:ss
    const start = startDateTime.value.replace('T', ' ')
    const end = endDateTime.value.replace('T', ' ')
    stats.value = await getDashboardStats(start, end)
  } catch (error) {
    console.error(error)
    toast.showToast('加载数据失败', 'error')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // Default to 7 days
  selectRange('7d')
})
</script>

<style scoped>
.analytics-page {
  width: 100%;
}

.chart-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 0.75rem;
  padding: 1.5rem;
}

.chart-title {
  font-size: 1.1rem;
  color: #d4b383;
  margin: 0 0 1rem 0;
  font-weight: 500;
}

.chart {
  height: 100%;
  width: 100%;
}
</style>
