<script lang="ts" setup>
import { computed } from 'vue'

interface Milestone {
  id: number
  stage: string
  reached_at: string | null
  note: string | null
}

interface Props {
  milestones: Milestone[]
  editable?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  editable: false,
})

const emit = defineEmits<{
  markReached: [stage: string, note: string]
}>()

interface StageDef {
  stage: string
  label: string
  customerMessage: string
  icon: string
}

const STAGES: StageDef[] = [
  { stage: 'ordered',           label: 'Ordered',            customerMessage: "We've received your order. The hardware order will be placed with our supplier within 24 hours.",                                              icon: 'tabler-receipt' },
  { stage: 'hardware_acquired', label: 'Hardware acquired',  customerMessage: 'Hardware ordered and en route to our Atlanta datacenter (typically 2-3 days).',                                                              icon: 'tabler-truck-delivery' },
  { stage: 'assembly',          label: 'Assembly',           customerMessage: 'Server received in Atlanta. Our DC tech is configuring iDRAC, BOSS boot, and base BIOS settings.',                                          icon: 'tabler-tools' },
  { stage: 'racked',            label: 'Racked & online',    customerMessage: 'Server racked, powered up, and online for final QA testing.',                                                                              icon: 'tabler-server' },
  { stage: 'deployed',          label: 'Deployed',           customerMessage: 'Server is live. Root credentials and iDRAC access have been emailed to you.',                                                              icon: 'tabler-circle-check' },
]

interface RowState extends StageDef {
  reachedAt: Date | null
  note: string | null
  isReached: boolean
  isCurrent: boolean
}

const rows = computed<RowState[]>(() => {
  // Build a quick lookup by stage
  const milestoneByStage = new Map<string, Milestone>()
  for (const m of props.milestones) milestoneByStage.set(m.stage, m)

  // Find the highest stage that has reached_at — that's the "current" stage
  let currentIdx = -1
  for (let i = STAGES.length - 1; i >= 0; i--) {
    const m = milestoneByStage.get(STAGES[i].stage)
    if (m?.reached_at) {
      currentIdx = i
      break
    }
  }

  return STAGES.map((s, idx) => {
    const m = milestoneByStage.get(s.stage)
    return {
      ...s,
      reachedAt: m?.reached_at ? new Date(m.reached_at) : null,
      note: m?.note ?? null,
      isReached: !!m?.reached_at,
      isCurrent: idx === currentIdx + 1, // next not-yet-reached
    }
  })
})

function formatDate(d: Date): string {
  return d.toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    timeZoneName: 'short',
  })
}

function markReached(stage: string): void {
  emit('markReached', stage, '')
}
</script>

<template>
  <VCard class="build-status pa-6" variant="outlined">
    <div class="build-status__head mb-5">
      <div class="d-flex align-center ga-2 mb-2">
        <VIcon icon="tabler-progress" color="primary" />
        <h3 class="text-h6 font-weight-bold mb-0">Build progress</h3>
      </div>
      <p class="text-body-2 text-medium-emphasis mb-0">
        Track your dedicated server build from order to live deployment.
      </p>
    </div>

    <div class="build-status__timeline">
      <div
        v-for="(row, idx) in rows"
        :key="row.stage"
        class="build-status__step"
        :class="{
          'build-status__step--reached': row.isReached,
          'build-status__step--current': row.isCurrent,
          'build-status__step--editable': editable && !row.isReached,
        }"
      >
        <div class="build-status__connector" v-if="idx > 0" />

        <div class="build-status__icon-wrap">
          <VIcon :icon="row.isReached ? 'tabler-circle-check-filled' : row.icon" size="24" />
        </div>

        <div class="build-status__body">
          <div class="d-flex align-center justify-space-between flex-wrap ga-2">
            <h4 class="build-status__step-title">{{ row.label }}</h4>
            <div v-if="row.reachedAt" class="text-caption text-medium-emphasis">
              {{ formatDate(row.reachedAt) }}
            </div>
            <VBtn
              v-else-if="editable"
              size="x-small"
              variant="tonal"
              color="primary"
              @click="markReached(row.stage)"
            >
              Mark reached
            </VBtn>
          </div>
          <p class="text-body-2 text-medium-emphasis mt-1 mb-0">{{ row.customerMessage }}</p>
          <p v-if="row.note" class="text-caption mt-2 mb-0 build-status__note">
            <VIcon icon="tabler-message" size="12" class="me-1" />
            {{ row.note }}
          </p>
        </div>
      </div>
    </div>
  </VCard>
</template>

<style lang="scss" scoped>
.build-status__timeline {
  display: flex;
  flex-direction: column;
  gap: 6px;
  position: relative;
}

.build-status__step {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 12px 0;
  position: relative;
  opacity: 0.55;

  &--reached {
    opacity: 1;
  }

  &--current {
    opacity: 1;
  }
}

.build-status__connector {
  position: absolute;
  left: 23px;
  top: -6px;
  width: 2px;
  height: 18px;
  background: rgba(var(--v-theme-on-surface), 0.15);
}

.build-status__step--reached .build-status__connector {
  background: rgb(var(--v-theme-primary));
}

.build-status__icon-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 46px;
  height: 46px;
  border-radius: 50%;
  background: rgba(var(--v-theme-on-surface), 0.06);
  flex-shrink: 0;
  z-index: 1;

  .v-icon {
    color: rgba(var(--v-theme-on-surface), 0.6);
  }
}

.build-status__step--reached .build-status__icon-wrap {
  background: rgba(var(--v-theme-primary), 0.15);

  .v-icon {
    color: rgb(var(--v-theme-primary));
  }
}

.build-status__step--current .build-status__icon-wrap {
  background: rgba(var(--v-theme-primary), 0.08);
  border: 2px dashed rgba(var(--v-theme-primary), 0.5);
  animation: build-status-pulse 2s ease-in-out infinite;

  .v-icon {
    color: rgb(var(--v-theme-primary));
  }
}

.build-status__step-title {
  font-size: 15px;
  font-weight: 700;
  margin-bottom: 0;
}

.build-status__note {
  background: rgba(var(--v-theme-on-surface), 0.04);
  padding: 6px 10px;
  border-radius: 6px;
  display: inline-flex;
  align-items: center;
}

.build-status__body {
  flex-grow: 1;
}

@keyframes build-status-pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.05); }
}
</style>
