import type {
  CourseProgressType,
  CourseStatisticsType,
  DashboardConfigType,
  DashboardType,
} from "@/gql/graphql";
import {
  fetchDashboardConfig,
  fetchProgressData,
  fetchStatisticData,
} from "@/services/dashboard";
import { defineStore } from "pinia";
import type { Ref } from "vue";
import { ref } from "vue";

export const useDashboardStore = defineStore("dashboard", () => {
  const dashboardConfigs: Ref<DashboardConfigType[]> = ref([]);
  const currentDashboardConfig: Ref<DashboardConfigType | undefined> = ref();
  const dashBoardDataCache: Record<
    string,
    CourseStatisticsType | CourseProgressType | null
  > = {};
  const currentDashBoardData: Ref<CourseStatisticsType | CourseProgressType | null> =
    ref(null);
  const loading = ref(false);

  const loadDashboardData = async (type: DashboardType, id: string) => {
    let data;
    switch (type) {
      case "STATISTICS_DASHBOARD":
        data = await fetchStatisticData(id);
        break;
      case "PROGRESS_DASHBOARD":
        data = await fetchProgressData(id);
        break;
      default:
        return;
    }
    dashBoardDataCache[id] = data;
    currentDashBoardData.value = data;
  };

  const switchAndLoadDashboardConfig = async (config: DashboardConfigType) => {
    currentDashboardConfig.value = config;
    await loadDashboardDetails();
  };

  const loadDashboardConfig = async () => {
    if (dashboardConfigs.value.length > 0) return;
    const configData = await fetchDashboardConfig();
    if (configData && configData.length > 0) {
      dashboardConfigs.value = configData;
      await switchAndLoadDashboardConfig(configData[0]);
    }
  };

  const loadDashboardDetails = async () => {
    loading.value = true;
    try {
      if (!currentDashboardConfig.value) {
        await loadDashboardConfig();
        return;
      }
      const { id, dashboard_type } = currentDashboardConfig.value;
      if (dashBoardDataCache[id]) {
        currentDashBoardData.value = dashBoardDataCache[id];
        return;
      }
      await loadDashboardData(dashboard_type, id);
    } finally {
      loading.value = false;
    }
  };

  return {
    dashboardConfigs,
    currentDashboardConfig,
    switchAndLoadDashboardConfig,
    loadDashboardConfig,
    loadDashboardDetails,
    currentDashBoardData,
    loading,
  };
});
