<script setup lang="ts">
import { onMounted, computed, ref } from 'vue'
import { useAuthStore } from '../stores/auth'
import { useActivitiesStore } from '../stores/activities'
import { useCoachingStore } from '../stores/coaching'
import type { FitnessEntry, WeeklyStats, PersonalRecord, TodayWorkout } from '../types/models'
import Card from 'primevue/card'
import Tag from 'primevue/tag'
import { useRouter } from 'vue-router'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TooltipComponent, LegendComponent, GridComponent,
} from 'echarts/components'
import VChart from 'vue-echarts'

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

const auth = useAuthStore()
const store = useActivitiesStore()
const coaching = useCoachingStore()
const router = useRouter()

const recentActivities = computed(() => store.activities.slice(0, 5))
const fitness = ref<FitnessEntry[]>([])
const weeklyStats = ref<WeeklyStats[]>([])
const records = ref<PersonalRecord[]>([])
const todayWorkout = ref<TodayWorkout | null>(null)

function formatDurationLabel(seconds: number): string {
  if (seconds < 60) return `${seconds}s`
  if (seconds < 3600) return `${seconds / 60}m`
  return `${seconds / 3600}h`
}

function formatDuration(seconds: number): string {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  return h > 0 ? `${h}h ${m}m` : `${m}m`
}

function formatDistance(meters: number | null): string {
  if (!meters) return '—'
  return `${(meters / 1000).toFixed(1)} km`
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })
}

function buildFitnessChart() {
  if (fitness.value.length === 0) return null

  const dates = fitness.value.map(e => e.date)
  const ctlData = fitness.value.map(e => e.ctl)
  const atlData = fitness.value.map(e => e.atl)
  const tsbData = fitness.value.map(e => e.tsb)

  return {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const date = params[0].name
        return `<b>${date}</b><br/>` +
          params.map((p: any) => `${p.marker} ${p.seriesName}: <b>${p.value.toFixed(1)}</b>`).join('<br/>')
      },
    },
    legend: { data: ['Fitness (CTL)', 'Fatigue (ATL)', 'Form (TSB)'], top: 0, textStyle: { color: '#6b7280', fontSize: 11 } },
    grid: { left: 40, right: 20, top: 40, bottom: 30 },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: { color: '#6b7280', fontSize: 10, formatter: (v: string) => { const d = new Date(v); return `${d.getDate()}/${d.getMonth() + 1}` } },
      splitLine: { show: false },
    },
    yAxis: { type: 'value', axisLabel: { color: '#6b7280' }, splitLine: { lineStyle: { color: '#e5e7eb' } } },
    series: [
      { name: 'Fitness (CTL)', type: 'line', data: ctlData, showSymbol: false, lineStyle: { width: 2 }, itemStyle: { color: '#3b82f6' } },
      { name: 'Fatigue (ATL)', type: 'line', data: atlData, showSymbol: false, lineStyle: { width: 2 }, itemStyle: { color: '#ef4444' } },
      {
        name: 'Form (TSB)', type: 'line', data: tsbData, showSymbol: false, lineStyle: { width: 2 }, itemStyle: { color: '#10b981' },
        areaStyle: {
          color: {
            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(16,185,129,0.15)' },
              { offset: 0.5, color: 'rgba(16,185,129,0)' },
              { offset: 0.5, color: 'rgba(239,68,68,0)' },
              { offset: 1, color: 'rgba(239,68,68,0.1)' },
            ],
          },
        },
      },
    ],
  }
}

function buildWeeklyChart() {
  if (weeklyStats.value.length === 0) return null

  const weeks = weeklyStats.value.map(w => {
    const d = new Date(w.week)
    return `${d.getDate()}/${d.getMonth() + 1}`
  })

  return {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const week = params[0].name
        return `<b>Week of ${week}</b><br/>` +
          params.map((p: any) => `${p.marker} ${p.seriesName}: <b>${p.value}</b>`).join('<br/>')
      },
    },
    legend: { data: ['Distance (km)', 'TSS', 'Hours'], top: 0, textStyle: { color: '#6b7280', fontSize: 11 } },
    grid: { left: 40, right: 40, top: 40, bottom: 30 },
    xAxis: { type: 'category', data: weeks, axisLabel: { color: '#6b7280', fontSize: 10 } },
    yAxis: [
      { type: 'value', axisLabel: { color: '#6b7280' }, splitLine: { lineStyle: { color: '#e5e7eb' } } },
      { type: 'value', axisLabel: { color: '#6b7280' }, splitLine: { show: false } },
    ],
    series: [
      {
        name: 'Distance (km)', type: 'bar', data: weeklyStats.value.map(w => w.distance),
        itemStyle: { color: '#3b82f6', borderRadius: [4, 4, 0, 0] }, barMaxWidth: 30,
      },
      {
        name: 'TSS', type: 'bar', data: weeklyStats.value.map(w => w.tss),
        itemStyle: { color: '#a855f7', borderRadius: [4, 4, 0, 0] }, barMaxWidth: 30,
      },
      {
        name: 'Hours', type: 'line', yAxisIndex: 1,
        data: weeklyStats.value.map(w => +(w.duration / 3600).toFixed(1)),
        showSymbol: true, symbolSize: 6, itemStyle: { color: '#10b981' }, lineStyle: { width: 2 },
      },
    ],
  }
}

onMounted(async () => {
  store.fetchActivities(5)
  try {
    fitness.value = await store.fetchFitness(90)
  } catch {
    // Fitness data may not be available yet
  }
  try {
    weeklyStats.value = await store.fetchWeeklyStats(8)
  } catch {
    // Weekly stats may not be available yet
  }
  try {
    records.value = await store.fetchPersonalRecords()
  } catch {
    // PR data may not be available yet
  }
  try {
    todayWorkout.value = await coaching.fetchTodayWorkout()
  } catch {
    // No active plan
  }
})
</script>

<template>
  <div>
    <h1 class="text-2xl font-semibold mb-6">Dashboard</h1>

    <!-- Rider stats cards -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 mb-8">
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">FTP</p>
          <p class="text-2xl font-bold">{{ auth.rider?.ftp ?? '—' }} <span class="text-sm text-surface-500 font-normal">W</span></p>
        </template>
      </Card>
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">Weight</p>
          <p class="text-2xl font-bold">{{ auth.rider?.weight ?? '—' }} <span class="text-sm text-surface-500 font-normal">kg</span></p>
        </template>
      </Card>
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">W/kg</p>
          <p class="text-2xl font-bold">
            {{ auth.rider?.ftp && auth.rider?.weight ? (auth.rider.ftp / auth.rider.weight).toFixed(2) : '—' }}
          </p>
        </template>
      </Card>
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">Total Rides</p>
          <p class="text-2xl font-bold">{{ store.total }}</p>
        </template>
      </Card>
    </div>

    <!-- Today's Workout -->
    <Card v-if="todayWorkout" class="mb-8 border-l-4 border-l-primary cursor-pointer hover:shadow-md transition-shadow" @click="router.push({ name: 'coach' })">
      <template #content>
        <div class="flex items-center justify-between">
          <div>
            <div class="flex items-center gap-2 mb-1">
              <i class="pi pi-bolt text-primary"></i>
              <p class="text-surface-500 text-xs uppercase">Тренировка на сегодня</p>
            </div>
            <p class="text-lg font-bold">{{ todayWorkout.title }}</p>
            <p v-if="todayWorkout.description" class="text-surface-500 text-sm mt-1 line-clamp-2">{{ todayWorkout.description }}</p>
          </div>
          <div class="flex items-center gap-3">
            <Tag :value="todayWorkout.workout_type" severity="info" />
            <div v-if="todayWorkout.duration_minutes" class="text-right">
              <p class="text-sm font-semibold">{{ todayWorkout.duration_minutes }} мин</p>
              <p v-if="todayWorkout.target_tss" class="text-xs text-surface-400">TSS {{ todayWorkout.target_tss }}</p>
            </div>
            <i class="pi pi-chevron-right text-surface-300"></i>
          </div>
        </div>
      </template>
    </Card>

    <!-- Personal Records -->
    <Card v-if="records.length > 0" class="mb-8">
      <template #title>
        <div class="flex items-center gap-2">
          <i class="pi pi-trophy text-amber-500"></i>
          Personal Records
        </div>
      </template>
      <template #content>
        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
          <div
            v-for="pr in records"
            :key="pr.duration"
            class="bg-surface-50 rounded-lg p-3 text-center border border-surface-200 cursor-pointer hover:border-primary transition-colors"
            @click="router.push({ name: 'activity-detail', params: { id: pr.activity_id } })"
          >
            <p class="text-surface-500 text-xs uppercase mb-1">{{ formatDurationLabel(pr.duration) }}</p>
            <p class="text-xl font-bold">{{ pr.power }}<span class="text-sm font-normal text-surface-500">W</span></p>
            <p v-if="auth.rider?.weight" class="text-xs text-surface-400">{{ (pr.power / auth.rider.weight).toFixed(1) }} W/kg</p>
          </div>
        </div>
      </template>
    </Card>

    <!-- Fitness trend chart -->
    <Card v-if="fitness.length > 0" class="mb-8">
      <template #title>Fitness Trend</template>
      <template #content>
        <VChart :option="buildFitnessChart() ?? undefined" style="height: 280px" autoresize />
        <div class="flex items-center justify-center gap-6 mt-2 text-xs text-surface-500">
          <span>CTL: chronic training load (fitness)</span>
          <span>ATL: acute training load (fatigue)</span>
          <span>TSB: training stress balance (form)</span>
        </div>
      </template>
    </Card>

    <!-- Weekly summary -->
    <Card v-if="weeklyStats.length > 0" class="mb-8">
      <template #title>Weekly Summary</template>
      <template #content>
        <VChart :option="buildWeeklyChart() ?? undefined" style="height: 280px" autoresize />
      </template>
    </Card>

    <!-- Recent rides -->
    <h2 class="text-lg font-semibold mb-4">Recent Rides</h2>
    <div v-if="recentActivities.length === 0" class="text-surface-500">
      No activities yet. Upload your first .FIT file!
    </div>
    <div v-else class="flex flex-col gap-3">
      <Card
        v-for="a in recentActivities"
        :key="a.id"
        class="cursor-pointer hover:border-primary transition-colors"
        @click="router.push({ name: 'activity-detail', params: { id: a.id } })"
      >
        <template #content>
          <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-2">
            <div class="flex items-center gap-3">
              <div>
                <p class="font-semibold">{{ a.name || 'Ride' }}</p>
                <p class="text-surface-500 text-sm">{{ formatDate(a.date) }}</p>
              </div>
              <Tag :value="a.activity_type" severity="info" class="text-xs" />
            </div>
            <div class="flex items-center gap-4 md:gap-6 text-sm flex-wrap">
              <div class="text-center">
                <p class="text-surface-500 text-xs">Duration</p>
                <p class="font-semibold">{{ formatDuration(a.duration) }}</p>
              </div>
              <div class="text-center">
                <p class="text-surface-500 text-xs">Distance</p>
                <p class="font-semibold">{{ formatDistance(a.distance) }}</p>
              </div>
              <div v-if="a.metrics?.avg_power" class="text-center">
                <p class="text-surface-500 text-xs">Power</p>
                <p class="font-semibold">{{ a.metrics.avg_power }}W</p>
              </div>
              <div v-if="a.metrics?.tss" class="text-center">
                <p class="text-surface-500 text-xs">TSS</p>
                <p class="font-semibold">{{ a.metrics.tss }}</p>
              </div>
              <div v-if="a.metrics?.normalized_power" class="text-center hidden md:block">
                <p class="text-surface-500 text-xs">NP</p>
                <p class="font-semibold">{{ a.metrics.normalized_power }}W</p>
              </div>
            </div>
          </div>
        </template>
      </Card>
    </div>
  </div>
</template>
