<script setup lang="ts">
import { ref, watch } from "vue";
import { apiGet } from "@/api/client";

interface Milestone {
  id: number;
  title: string;
  status: string;
}

const props = defineProps<{
  projectId: number | null;
  modelValue: number | null;
}>();

const emit = defineEmits<{
  (e: "update:modelValue", val: number | null): void;
}>();

const milestones = ref<Milestone[]>([]);
const loading = ref(false);

watch(
  () => props.projectId,
  async (pid) => {
    milestones.value = [];
    if (!pid) {
      emit("update:modelValue", null);
      return;
    }
    loading.value = true;
    try {
      const data = await apiGet<{ milestones: Milestone[] }>(
        `/api/projects/${pid}/milestones`
      );
      milestones.value = data.milestones.filter((m) => m.status === "active");
    } catch {
      milestones.value = [];
    } finally {
      loading.value = false;
    }
  },
  { immediate: true }
);

function onChange(e: Event) {
  const val = (e.target as HTMLSelectElement).value;
  emit("update:modelValue", val ? Number(val) : null);
}
</script>

<template>
  <select
    class="milestone-select"
    :value="modelValue ?? ''"
    :disabled="!projectId || loading"
    @change="onChange"
  >
    <option value="">{{ projectId ? "No milestone" : "(Select project first)" }}</option>
    <option v-for="m in milestones" :key="m.id" :value="m.id">
      {{ m.title }}
    </option>
  </select>
</template>

<style scoped>
.milestone-select {
  padding: 0.4rem 0.6rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  background: var(--color-bg);
  color: var(--color-text);
  font-size: 0.875rem;
  font-family: inherit;
  box-sizing: border-box;
  width: 100%;
}
.milestone-select:focus {
  outline: none;
  border-color: var(--color-primary);
}
.milestone-select:disabled {
  opacity: 0.5;
  cursor: default;
}
</style>
