import { itGet } from "@/fetchHelpers";
import type { Ref } from "vue";
import { ref, watchEffect } from "vue";

export interface Participant {
  id: string;
  first_name: string;
  last_name: string;
  email: string;
  username: string;
  avatar_url: string;
  language: string;
}

interface Circle {
  id: number;
  title: string;
}

enum CompletionStatus {
  UNKNOWN = "UNKNOWN",
  SUBMITTED = "SUBMITTED",
  EVALUATED = "EVALUATED",
}

interface Completion {
  status: CompletionStatus;
  user_id: string;
  last_name: string;
  url: string;
}

export interface Assignment {
  id: string;
  title: string;
  circle_id: string;
  pending_evaluations: number;
  completions: Completion[];
  type: string;
}

interface Summary {
  participants: Participant[];
  circles: Circle[];
  assignments: Assignment[];
}

export const useMentorCockpit = (
  courseSessionId: string | Ref<string> | (() => string)
) => {
  const isLoading = ref(false);
  const summary: Ref<Summary | null> = ref(null);
  const error = ref(null);

  const getCircleTitleById = (id: string): string => {
    if (summary.value?.circles) {
      const circle = summary.value.circles.find((circle) => String(circle.id) === id);
      return circle ? circle.title : "";
    }
    return "";
  };

  const getAssignmentById = (id: string): Assignment | null => {
    if (summary.value?.assignments) {
      const found = summary.value.assignments.find(
        (assignment) => assignment.id === id
      );
      return found ? found : null;
    }
    return null;
  };

  const fetchData = () => {
    summary.value = null;
    error.value = null;

    itGet(`/api/mentor/${courseSessionId}/summary`)
      .then((response) => {
        summary.value = response;
      })
      .catch((err) => (error.value = err))
      .finally(() => {
        isLoading.value = false;
      });
  };

  watchEffect(() => {
    fetchData();
  });

  return {
    isLoading,
    summary,
    error,
    getCircleTitleById,
    fetchData,
    getAssignmentById,
  };
};
