<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { configApi } from '../../services/configApi'
import type { StatusStage, NotificationEntry } from '../../types'

const props = defineProps<{ docNumber: string }>()

const stages = ref<StatusStage[]>([])
const history = ref<NotificationEntry[]>([])
const loading = ref(false)
const currentStageIndex = ref(-1)

async function load() {
  if (!props.docNumber) return
  loading.value = true
  try {
    const [stagesResp, historyResp] = await Promise.all([
      configApi.listStages(),
      configApi.getNotificationHistoryForDoc(props.docNumber),
    ])
    stages.value = stagesResp.data.stages
    history.value = historyResp.data.notifications

    // Determine current stage from latest notification
    if (history.value.length && stages.value.length) {
      const lastSent = history.value.find(n => n.status === 'sent')
      if (lastSent) {
        // Try to match subject to stage
        for (let i = stages.value.length - 1; i >= 0; i--) {
          if (lastSent.subject.toLowerCase().includes(stages.value[i].stage_key.toLowerCase()) ||
              lastSent.subject.toLowerCase().includes(stages.value[i].stage_label.toLowerCase())) {
            currentStageIndex.value = i
            break
          }
        }
      }
    }
  } catch {
    // silent
  } finally {
    loading.value = false
  }
}

function stageStatus(index: number): 'completed' | 'current' | 'upcoming' {
  if (currentStageIndex.value < 0) return 'upcoming'
  if (index < currentStageIndex.value) return 'completed'
  if (index === currentStageIndex.value) return 'current'
  return 'upcoming'
}

const statusColors = {
  completed: 'bg-green-500 border-green-500',
  current: 'bg-primary-500 border-primary-500 animate-pulse',
  upcoming: 'bg-dark-700 border-dark-600',
}

const lineColors = {
  completed: 'bg-green-500',
  current: 'bg-dark-600',
  upcoming: 'bg-dark-700',
}

watch(() => props.docNumber, load)
onMounted(load)
</script>

<template>
  <div v-if="stages.length" class="card">
    <h3 class="font-semibold text-sm mb-4">Status Timeline — {{ docNumber }}</h3>
    <div v-if="loading" class="text-dark-500 text-sm text-center py-2">Loading...</div>
    <div v-else class="flex items-start">
      <div v-for="(stage, i) in stages" :key="stage.id" class="flex-1 flex flex-col items-center relative">
        <!-- Connector line -->
        <div v-if="i > 0" :class="['absolute top-3 right-1/2 w-full h-0.5', lineColors[stageStatus(i)]]" />
        <!-- Dot -->
        <div :class="['w-6 h-6 rounded-full border-2 z-10 flex items-center justify-center', statusColors[stageStatus(i)]]">
          <svg v-if="stageStatus(i) === 'completed'" class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/>
          </svg>
        </div>
        <!-- Label -->
        <div class="mt-2 text-center">
          <div class="text-xs font-medium" :class="stageStatus(i) === 'upcoming' ? 'text-dark-500' : 'text-dark-200'">
            {{ stage.stage_label }}
          </div>
          <div class="text-[10px] text-dark-600">{{ stage.stage_key }}</div>
        </div>
      </div>
    </div>

    <!-- Recent notifications for this doc -->
    <div v-if="history.length" class="mt-4 border-t border-dark-700 pt-3">
      <div class="text-xs text-dark-400 mb-2">Recent notifications</div>
      <div v-for="n in history.slice(0, 5)" :key="n.id" class="flex items-center justify-between py-1 text-xs">
        <span class="text-dark-300 truncate flex-1">{{ n.subject }}</span>
        <span :class="n.status === 'sent' ? 'text-green-400' : n.status === 'failed' ? 'text-red-400' : 'text-yellow-400'" class="ml-2 font-medium">
          {{ n.status }}
        </span>
      </div>
    </div>
  </div>
  <div v-else-if="!loading" class="card">
    <p class="text-dark-500 text-sm text-center py-2">No status stages configured for this document type.</p>
  </div>
</template>
