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

import editorApi from "@/module/editor/service/editor-api";
import experimentApi from "@/module/experiment/service/experiment-api";
import {
  mapExperimentDetail,
  resolveExperimentBaseUrl,
} from "@/module/experiment/model/experiment-view-model";
import releaseApi from "@/module/release/service/release-api";
import variantApi from "@/module/variant/service/variant-api";
import {
  buildVariantEditorEntry,
  mapVariantChangeCards,
  mapVariantDetail,
  summarizeVariantChanges,
} from "@/module/variant/model/variant-view-model";

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

  const variant = ref(null);
  const experiment = ref(null);
  const releases = ref([]);
  const changes = ref([]);
  const loading = ref(false);
  const errorMessage = ref("");

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

  const changesSummary = computed(() => summarizeVariantChanges(changes.value));
  const changeCards = computed(() => mapVariantChangeCards(changes.value));
  const recommendedBaseUrl = computed(() => resolveExperimentBaseUrl(experiment.value));
  const editorEntry = computed(() =>
    buildVariantEditorEntry({
      variant: variant.value,
      changes: changes.value,
      baseUrl: recommendedBaseUrl.value,
    })
  );
  const latestRelease = computed(() => releases.value[0] || null);
  const nextStepSummary = computed(() => {
    if (changes.value.length === 0) {
      return {
        title: "先建立第一筆修改",
        description:
          "這個變體目前還沒有任何修改內容，先進編輯器建立第一筆變更，後面才能更有效檢查版本結果。",
        actionLabel: "開始修改這個變體",
        actionType: "editor",
      };
    }

    if (!latestRelease.value?.id) {
      return {
        title: "先確認最新版本",
        description:
          "目前這個變體已有修改內容，下一步適合先看最新版本是否已收進 runtime payload。",
        actionLabel: "查看最新版本",
        actionType: "release",
      };
    }

    return {
      title: "回到編輯器做細部調整",
      description:
        "目前已有變更與版本資訊，適合回到編輯器微調內容，再重新檢查畫面結果。",
      actionLabel: "進入編輯器",
      actionType: "editor",
    };
  });

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

    try {
      const variantItem = await variantApi.getVariant(variantId.value);
      const mappedVariant = mapVariantDetail(variantItem);
      variant.value = mappedVariant;

      const [experimentItem, changeItems, releaseItems] = await Promise.all([
        experimentApi.getExperiment(mappedVariant.experimentId),
        editorApi.getVariantChanges(mappedVariant.id),
        releaseApi.listReleases({ experimentId: mappedVariant.experimentId }),
      ]);

      experiment.value = mapExperimentDetail(experimentItem);
      changes.value = changeItems;
      releases.value = releaseItems;
    } catch (error) {
      errorMessage.value = error?.message || "無法載入 variant detail。";
      variant.value = null;
      experiment.value = null;
      releases.value = [];
      changes.value = [];
    } finally {
      loading.value = false;
    }
  };

  const openEditor = () => {
    if (!variant.value?.id) {
      return;
    }

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

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

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

  const openLatestRelease = () => {
    if (!latestRelease.value?.id) {
      return;
    }

    router.push({
      name: "release-detail",
      params: { releaseId: latestRelease.value.id },
    });
  };

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

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

  const runNextStep = () => {
    if (nextStepSummary.value.actionType === "release") {
      openLatestRelease();
      return;
    }

    openEditor();
  };

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

  return {
    route,
    loading,
    errorMessage,
    variant,
    experiment,
    releases,
    changes,
    changesSummary,
    changeCards,
    recommendedBaseUrl,
    editorEntry,
    latestRelease,
    nextStepSummary,
    loadPage,
    openEditor,
    openExperiment,
    openLatestRelease,
    goBack,
    runNextStep,
  };
}
