import { computed, onMounted, ref } from "vue"
import { useRouter } from "vue-router"

import experimentApi from "@/module/experiment/service/experiment-api"
import {
  mapExperimentListItem,
  statusTypeMap,
  summarizeExperiments,
} from "@/module/experiment/model/experiment-view-model"

export function useExperimentListPage() {
  const router = useRouter()
  const experiments = ref([])
  const loading = ref(false)
  const errorMessage = ref("")

  const summary = computed(() => summarizeExperiments(experiments.value))

  const loadExperiments = async () => {
    loading.value = true
    errorMessage.value = ""

    try {
      const items = await experimentApi.listExperiments()
      experiments.value = items.map(mapExperimentListItem)
    } catch (error) {
      experiments.value = []
      errorMessage.value = error?.message || "無法載入 experiment 列表。"
    } finally {
      loading.value = false
    }
  }

  const openExperiment = (experimentId) => {
    router.push({
      name: "experiment-detail",
      params: { experimentId },
    })
  }

  onMounted(async () => {
    await loadExperiments()
  })

  return {
    experiments,
    loading,
    errorMessage,
    summary,
    statusTypeMap,
    loadExperiments,
    openExperiment,
  }
}
