<script setup lang="ts">
import ItButton from "@/components/ui/ItButton.vue";
import ItCheckbox from "@/components/ui/ItCheckbox.vue";
import { ref } from "vue";
import { bustItGetCache } from "@/fetchHelpers";
import { useUserStore } from "@/stores/user";
import eventBus from "@/utils/eventBus";
import log from "loglevel";
import { useMutation } from "@urql/vue";
import { UPSERT_ASSIGNMENT_COMPLETION_MUTATION } from "@/graphql/mutations";
import type { Assignment } from "@/types";

const props = defineProps<{
  courseSessionId: string;
  assignment: Assignment;
  learningContentId: string;
}>();

const upsertAssignmentCompletionMutation = useMutation(
  UPSERT_ASSIGNMENT_COMPLETION_MUTATION
);

const confirmInput = ref(false);

const onSubmit = async () => {
  try {
    await upsertAssignmentCompletionMutation.executeMutation({
      assignmentId: props.assignment.id,
      courseSessionId: props.courseSessionId,
      learningContentId: props.learningContentId,
      completionDataString: JSON.stringify({}),
      completionStatus: "SUBMITTED",
    });
    bustItGetCache(
      `/api/course/completion/${props.courseSessionId}/${useUserStore().id}/`
    );
    // if solution sample is available, do not close the assigment automatically
    if (!props.assignment.solution_sample) {
      eventBus.emit("finishedLearningContent", true);
    }
  } catch (error) {
    log.error("Could not submit assignment", error);
  }
};
</script>

<template>
  <ItCheckbox
    class="w-full border-b border-gray-400 py-10 sm:py-6"
    :checkbox-item="{
      label: $t('assignment.confirmSubmitResults'),
      value: 'value',
      checked: confirmInput,
    }"
    data-cy="confirm-submit-results"
    @toggle="confirmInput = !confirmInput"
  ></ItCheckbox>
  <ItButton
    class="mt-6"
    variant="blue"
    size="large"
    :disabled="!confirmInput"
    data-cy="submit-assignment"
    @click="onSubmit"
  >
    <p>{{ $t("assignment.submitAssignment") }}</p>
  </ItButton>
</template>
