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

import experimentApi from "@/module/experiment/service/experiment-api";
import variantApi from "@/module/variant/service/variant-api";
import {
  mapExperimentDetail,
  resolveExperimentBaseUrl,
  statusTypeMap,
} from "@/module/experiment/model/experiment-view-model";
import releaseApi from "@/module/release/service/release-api";
import {
  buildReleaseReadiness,
  buildReleaseStatusTag,
  buildReleaseTitle,
  buildRuntimePayloadSummary,
  mapReleaseDetail,
} from "@/module/release/model/release-view-model";

export function useReleaseDetailPage() {
  const route = useRoute();
  const router = useRouter();

  const release = ref(null);
  const experiment = ref(null);
  const variants = ref([]);
  const loading = ref(false);
  const errorMessage = ref("");

  const releaseId = computed(() => String(route.params.releaseId || ""));
  const payloadSummary = computed(() =>
    buildRuntimePayloadSummary(release.value?.runtimePayload || {})
  );
  const releaseReadiness = computed(() =>
    buildReleaseReadiness({
      release: release.value,
      payloadSummary: payloadSummary.value,
    })
  );
  const releaseTitle = computed(() => buildReleaseTitle(release.value));
  const releaseStatusTag = computed(() =>
    buildReleaseStatusTag(release.value?.status)
  );
  const runtimePayloadPreview = computed(() =>
    JSON.stringify(release.value?.runtimePayload || {}, null, 2)
  );
  const recommendedBaseUrl = computed(() => resolveExperimentBaseUrl(experiment.value));
  const primaryVariant = computed(() => variants.value[0] || null);
  const nextStepSummary = computed(() => {
    if (payloadSummary.value.keyCount === 0) {
      return {
        title: "先回到主要變體補內容",
        description:
          "這個版本還沒有帶出 runtime payload，建議先回到主要變體編輯器，補上內容後再重新檢查。",
        actionLabel: "回到主要變體編輯器",
        actionType: "editor",
      };
    }

    return {
      title: "回畫面確認最新版本效果",
      description:
        "這個版本已有 payload，可先回主要變體編輯器，對照畫面與版本內容是否一致。",
      actionLabel: "前往主要變體編輯器",
      actionType: "editor",
    };
  });

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

    try {
      const releaseItem = await releaseApi.getRelease(releaseId.value);
      const mappedRelease = mapReleaseDetail(releaseItem);
      release.value = mappedRelease;
      const [experimentItem, variantItems] = await Promise.all([
        experimentApi.getExperiment(mappedRelease.experimentId),
        variantApi.listVariants({ experimentId: mappedRelease.experimentId }),
      ]);

      experiment.value = mapExperimentDetail(experimentItem);
      variants.value = variantItems;
    } catch (error) {
      errorMessage.value = error?.message || "無法載入 release detail。";
      release.value = null;
      experiment.value = null;
      variants.value = [];
    } finally {
      loading.value = false;
    }
  };

  const openExperiment = () => {
    if (!release.value?.experimentId) {
      return;
    }

    router.push({
      name: "experiment-detail",
      params: { experimentId: release.value.experimentId },
    });
  };

  const openPrimaryVariantEditor = () => {
    if (!primaryVariant.value?.id) {
      return;
    }

    router.push({
      name: "editor-variant",
      params: { variantId: primaryVariant.value.id },
      query: recommendedBaseUrl.value
        ? {
            base_url: recommendedBaseUrl.value,
          }
        : undefined,
    });
  };

  const goBack = () => {
    if (release.value?.experimentId) {
      openExperiment();
      return;
    }

    router.push({ name: "experiments" });
  };

  const runNextStep = () => {
    openPrimaryVariantEditor();
  };

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

  return {
    route,
    loading,
    errorMessage,
    release,
    experiment,
    variants,
    payloadSummary,
    releaseReadiness,
    releaseTitle,
    releaseStatusTag,
    runtimePayloadPreview,
    recommendedBaseUrl,
    primaryVariant,
    nextStepSummary,
    statusTypeMap,
    loadPage,
    openExperiment,
    openPrimaryVariantEditor,
    goBack,
    runNextStep,
  };
}
