<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="fs-input 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>
/* The input itself is the .fs-input canon (components.css); only the
   layout remainder lives here. */
.milestone-select {
  box-sizing: border-box;
  width: 100%;
}
</style>
