<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useWorkItemsStore } from '@/stores/workitems'
import { calculateSCurve, type CurvePoint, type SCurveMetrics, type SCurveData } from '@/services/s-curve'
import { getBlockers, getBlockerStats } from '@/services/blocker-log'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { TrendingUp, AlertTriangle } from 'lucide-vue-next'

const props = defineProps<{ projectId: number }>()

const workItems = useWorkItemsStore()
const loading = ref(true)
const sCurve = ref<SCurveData | null>(null)

async function load() {
  loading.value = true
  try {
    const blockers = await getBlockers(props.projectId)
    sCurve.value = calculateSCurve(workItems.userStories, blockers)
  } catch (e) {
    console.error('[Alpha] S-Curve error:', e)
  } finally {
    loading.value = false
  }
}

onMounted(load)
watch(() => workItems.userStories.length, load)

const CHART_W = 600
const CHART_H = 250
const PAD = { top: 20, right: 20, bottom: 35, left: 50 }

function buildPath(points: CurvePoint[], maxSp: number, totalDays: number): string {
  if (points.length === 0) return ''
  const w = CHART_W - PAD.left - PAD.right
  const h = CHART_H - PAD.top - PAD.bottom
  const firstDate = points[0].date
  return points.map((p, i) => {
    const first = new Date(firstDate)
    const cur = new Date(p.date)
    const dx = Math.max(0, Math.ceil((cur.getTime() - first.getTime()) / (1000 * 60 * 60 * 24)))
    const x = PAD.left + (dx / totalDays) * w
    const y = PAD.top + h - (p.cumulative / maxSp) * h
    return `${i === 0 ? 'M' : 'L'}${x},${y}`
  }).join(' ')
}

const planned = computed(() => sCurve.value?.planned || [])
const actual = computed(() => sCurve.value?.actual || [])
const metrics = computed(() => sCurve.value?.metrics)

const maxSp = computed(() => {
  const all = [...planned.value, ...actual.value]
  return Math.max(...all.map(p => p.cumulative), 1)
})

const totalDays = computed(() => {
  const all = [...planned.value, ...actual.value]
  if (all.length < 2) return 30
  const first = new Date(all[0].date)
  const last = new Date(all[all.length - 1].date)
  return Math.max(1, Math.ceil((last.getTime() - first.getTime()) / (1000 * 60 * 60 * 24)))
})
</script>

<template>
  <Card id="scurve-chart">
    <CardHeader class="pb-3">
      <CardTitle class="text-sm font-medium flex items-center gap-2">
        <TrendingUp class="size-4" />
        Curva S del proyecto
      </CardTitle>
    </CardHeader>
    <CardContent>
      <div v-if="loading" class="text-xs text-muted-foreground text-center py-8">Cargando...</div>

      <div v-else-if="planned.length === 0" class="text-xs text-muted-foreground text-center py-8">
        No hay suficientes datos. Se necesitan HUs con story points y fechas.
      </div>

      <div v-else class="space-y-4">
        <!-- Metrics row -->
        <div v-if="metrics" class="grid grid-cols-4 gap-2 text-xs">
          <div class="p-2 rounded-lg bg-muted/30">
            <span class="text-muted-foreground">SP total</span>
            <p class="font-bold text-sm">{{ metrics.totalSpPlanned }}</p>
          </div>
          <div class="p-2 rounded-lg bg-muted/30">
            <span class="text-muted-foreground">Velocidad/sem</span>
            <p class="font-bold text-sm">{{ metrics.velocityPerWeek }} SP</p>
          </div>
          <div class="p-2 rounded-lg bg-muted/30">
            <span class="text-muted-foreground">SPI</span>
            <p class="font-bold text-sm" :class="metrics.spi >= 1 ? 'text-green-500' : 'text-red-500'">
              {{ metrics.spi }}
            </p>
          </div>
          <div class="p-2 rounded-lg bg-muted/30">
            <span class="text-muted-foreground">Proyección</span>
            <p class="font-bold text-sm">{{ metrics.estimatedEndDate || '—' }}</p>
          </div>
        </div>

        <!-- Blockers summary -->
        <div v-if="metrics && metrics.totalBlockedHours > 0" class="flex items-center gap-2 text-xs p-2 rounded-lg bg-orange-500/5 border border-orange-500/20">
          <AlertTriangle class="size-3.5 text-orange-500 shrink-0" />
          <span class="text-muted-foreground">
            <strong class="text-orange-600">{{ metrics.totalBlockedHours }}h</strong> bloqueadas
            (<strong class="text-orange-600">{{ metrics.clientBlockedHours }}h</strong> imputables al cliente)
          </span>
        </div>

        <!-- SVG Chart -->
        <svg :viewBox="`0 0 ${CHART_W} ${CHART_H}`" class="w-full h-auto">
          <line v-for="i in 5" :key="i"
            :x1="PAD.left" :y1="PAD.top + ((i-1)/4) * (CHART_H - PAD.top - PAD.bottom)"
            :x2="CHART_W - PAD.right" :y2="PAD.top + ((i-1)/4) * (CHART_H - PAD.top - PAD.bottom)"
            stroke="currentColor" stroke-opacity="0.1" stroke-dasharray="4,4"
          />
          <path :d="buildPath(planned, maxSp, totalDays)" fill="none" stroke="#3b82f6" stroke-width="2" />
          <path :d="buildPath(actual, maxSp, totalDays)" fill="none" stroke="#22c55e" stroke-width="2" />

          <text v-for="i in 5" :key="'y'+i"
            :x="PAD.left - 8"
            :y="PAD.top + ((i-1)/4) * (CHART_H - PAD.top - PAD.bottom) + 4"
            text-anchor="end" class="fill-muted-foreground text-[10px]"
          >{{ Math.round(maxSp * (i-1) / 4) }}</text>

          <text :x="PAD.left" :y="CHART_H - 5" text-anchor="middle" class="fill-muted-foreground text-[9px]">
            {{ planned[0]?.date?.slice(5) || '' }}
          </text>
          <text :x="(CHART_W - PAD.right + PAD.left) / 2" :y="CHART_H - 5" text-anchor="middle" class="fill-muted-foreground text-[9px]">
            {{ planned[Math.floor(planned.length/2)]?.date?.slice(5) || '' }}
          </text>
          <text :x="CHART_W - PAD.right" :y="CHART_H - 5" text-anchor="middle" class="fill-muted-foreground text-[9px]">
            {{ planned[planned.length - 1]?.date?.slice(5) || '' }}
          </text>

          <line x1="20" y1="12" x2="40" y2="12" stroke="#3b82f6" stroke-width="2" />
          <text x="45" y="16" class="fill-muted-foreground text-[9px]">Plan</text>
          <line x1="90" y1="12" x2="110" y2="12" stroke="#22c55e" stroke-width="2" />
          <text x="115" y="16" class="fill-muted-foreground text-[9px]">Real</text>
        </svg>
      </div>
    </CardContent>
  </Card>
</template>
