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

import experimentApi from "@/module/experiment/service/experiment-api"
import releaseApi from "@/module/release/service/release-api"
import variantApi from "@/module/variant/service/variant-api"
import {
  mapExperimentDetail,
  mapReleaseItem,
  mapVariantItem,
  resolveExperimentBaseUrl,
} from "@/module/experiment/model/experiment-view-model"

export function useExperimentDetailPage() {
  const route = useRoute()
  const router = useRouter()
  const experiment = ref(null)
  const variants = ref([])
  const releases = ref([])
  const goals = ref([])
  const activityLog = ref([])
  const errorMessage = ref("")

  const experimentId = computed(() => String(route.params.experimentId || ""))

  const recommendedBaseUrl = computed(() =>
    resolveExperimentBaseUrl(experiment.value)
  )
  const latestRelease = computed(() => releases.value[0] || null)

  const loadPage = async () => {
    errorMessage.value = ""
    try {
      const [experimentItem, variantItems, releaseItems] = await Promise.all([
        experimentApi.getExperiment(experimentId.value),
        variantApi.listVariants({ experimentId: experimentId.value }),
        releaseApi.listReleases({ experimentId: experimentId.value }),
      ])

      const mapped = mapExperimentDetail(experimentItem)
      experiment.value = mapped
      variants.value = variantItems.map(mapVariantItem)
      releases.value = releaseItems.map(mapReleaseItem)

      if (mapped.siteId) {
        try {
          goals.value = await experimentApi.listGoals({ siteId: mapped.siteId })
        } catch {
          goals.value = []
        }
      }

      try {
        activityLog.value = await experimentApi.listActivity(experimentId.value)
      } catch {
        activityLog.value = []
      }
    } catch (error) {
      errorMessage.value = error?.message || "無法載入實驗詳情。"
      experiment.value = null
      variants.value = []
      releases.value = []
      goals.value = []
      activityLog.value = []
    }
  }

  const saveExperimentSettings = async (payload) => {
    await experimentApi.updateExperiment(experimentId.value, payload)
    await loadPage()
  }

  const buildRelease = async () => {
    await releaseApi.buildRelease(experimentId.value)
    await loadPage()
  }

  const publishRelease = async (releaseId) => {
    await releaseApi.publishRelease(releaseId)
    await loadPage()
  }

  const rollbackRelease = async (releaseId) => {
    await releaseApi.rollbackRelease(releaseId)
    await loadPage()
  }

  const archiveRelease = async (releaseId) => {
    await releaseApi.archiveRelease(releaseId)
    await loadPage()
  }

  const goBack = () => {
    router.push({ name: "experiments" })
  }

  const openEditor = (variantId) => {
    router.push({
      name: "editor-variant",
      params: { variantId },
      query: recommendedBaseUrl.value ? { base_url: recommendedBaseUrl.value } : undefined,
    })
  }

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

  return {
    route,
    experimentId,
    experiment,
    variants,
    releases,
    goals,
    activityLog,
    errorMessage,

    recommendedBaseUrl,
    latestRelease,
    loadPage,
    saveExperimentSettings,
    buildRelease,
    publishRelease,
    rollbackRelease,
    archiveRelease,
    goBack,
    openEditor,
  }
}
