import { onMounted, onUnmounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useMdtodoReportPreview } from "@/composables/mdtodo/useMdtodoReportPreview";
import { useMdtodoRouteSelection } from "@/composables/mdtodo/useMdtodoRouteSelection";
import { useMdtodoSource } from "@/composables/mdtodo/useMdtodoSource";
import { useMdtodoTaskData } from "@/composables/mdtodo/useMdtodoTaskData";
import { useMdtodoTaskMutation } from "@/composables/mdtodo/useMdtodoTaskMutation";
import { useMdtodoViewState } from "@/composables/mdtodo/useMdtodoViewState";
import { useMdtodoWorkbenchLaunch } from "@/composables/mdtodo/useMdtodoWorkbenchLaunch";
import { useMdtodoWorkspaceActions } from "@/composables/mdtodo/useMdtodoWorkspaceActions";
import { useMdtodoWorkspaceNavigation } from "@/composables/mdtodo/useMdtodoWorkspaceNavigation";
import { useMdtodoWorkspaceState } from "@/composables/mdtodo/useMdtodoWorkspaceState";

export { type MdtodoRefreshMode } from "@/composables/mdtodo/useMdtodoWorkspaceState";

export function useMdtodoWorkspaceController() {
  const router = useRouter();
  const route = useRoute();
  const selection = useMdtodoRouteSelection({ router, route });
  const source = useMdtodoSource();
  const taskData = useMdtodoTaskData();
  const mutation = useMdtodoTaskMutation();
  const report = useMdtodoReportPreview();
  const launch = useMdtodoWorkbenchLaunch(router);
  const viewState = useMdtodoViewState(router, route);
  const state = useMdtodoWorkspaceState({ source, taskData, report, launch, viewState });
  const navigation = useMdtodoWorkspaceNavigation({ router, route, selection, source, taskData, report, viewState, state });
  const actions = useMdtodoWorkspaceActions({ router, route, source, taskData, mutation, report, launch, viewState, state, navigation });
  let queryTimer: ReturnType<typeof setTimeout> | null = null;

  watch(state.selectedTaskRef, (taskRef) => {
    void Promise.all([taskData.loadLinks(taskRef), taskData.loadTaskDetail(taskRef)]);
  });
  watch(state.selectedTask, actions.resetEditor, { immediate: true });
  watch(taskData.taskDetail, (detail) => {
    if (detail?.taskRef === state.selectedTaskRef.value && !state.editingBody.value)
      state.editBody.value = detail.body || "";
  });
  watch([state.taskSearch, state.taskStatus], () => {
    if (queryTimer) clearTimeout(queryTimer);
    queryTimer = setTimeout(() => void navigation.reloadWindow(), 250);
  });
  watch(
    () => route.fullPath,
    () => {
      if (!state.loading.value && source.sources.value.length)
        void navigation.applyRoute();
    },
  );
  onMounted(() => {
    void actions.loadProviders();
    void navigation.loadPage();
  });
  onUnmounted(() => {
    if (queryTimer) clearTimeout(queryTimer);
  });

  return {
    router,
    route,
    selection,
    source,
    taskData,
    mutation,
    report,
    launch,
    viewState,
    ...state,
    ...navigation,
    ...actions,
  };
}
