<script setup lang="ts">
import ItButton from "@/components/ui/ItButton.vue";
import ItCheckbox from "@/components/ui/ItCheckbox.vue";
import ItSuccessAlert from "@/components/ui/ItSuccessAlert.vue";
import { useCurrentCourseSession } from "@/composables";
import { UPSERT_ASSIGNMENT_COMPLETION_MUTATION } from "@/graphql/mutations";
import AssignmentSubmissionResponses from "@/pages/learningPath/learningContentPage/assignment/AssignmentSubmissionResponses.vue";
import { useCourseSessionsStore } from "@/stores/courseSessions";
import type { Assignment, AssignmentCompletion, AssignmentTask } from "@/types";
import { useMutation } from "@urql/vue";
import type { Dayjs } from "dayjs";
import log from "loglevel";
import { computed, reactive } from "vue";
import { useI18n } from "vue-i18n";

const props = defineProps<{
  assignment: Assignment;
  assignmentCompletion?: AssignmentCompletion;
  courseSessionId: number;
  dueDate: Dayjs;
}>();

const emit = defineEmits<{
  (e: "editTask", task: AssignmentTask): void;
}>();

const courseSessionsStore = useCourseSessionsStore();
const courseSession = useCurrentCourseSession();
const { t } = useI18n();

const state = reactive({
  confirmInput: false,
  confirmPerson: false,
});

const circleExpert = computed(() => {
  return courseSessionsStore.circleExperts[0];
});

const circleExpertName = computed(() => {
  return `${circleExpert.value?.first_name} ${circleExpert.value?.last_name}`;
});

const completionStatus = computed(() => {
  return props.assignmentCompletion?.completion_status ?? "IN_PROGRESS";
});

const completionData = computed(() => {
  return props.assignmentCompletion?.completion_data ?? {};
});

const upsertAssignmentCompletionMutation = useMutation(
  UPSERT_ASSIGNMENT_COMPLETION_MUTATION
);

const onEditTask = (task: AssignmentTask) => {
  emit("editTask", task);
};

const onSubmit = async () => {
  try {
    // noinspection TypeScriptValidateTypes
    upsertAssignmentCompletionMutation.executeMutation({
      assignmentId: props.assignment.id.toString(),
      courseSessionId: courseSession.value.id.toString(),
      completionDataString: JSON.stringify({}),
      completionStatus: "SUBMITTED",
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      id: props.assignmentCompletion?.id,
    });
  } catch (error) {
    log.error("Could not submit assignment", error);
  }
};
</script>
<template>
  <div class="w-full border border-gray-400 p-8">
    <h3 class="heading-3 border-b border-gray-400 pb-6">
      {{ $t("assignment.acceptConditionsDisclaimer") }}
    </h3>

    <div v-if="completionStatus === 'IN_PROGRESS'">
      <ItCheckbox
        class="w-full border-b border-gray-400 py-10 sm:py-6"
        :checkbox-item="{
          label: $t('assignment.confirmSubmitResults'),
          value: 'value',
          checked: state.confirmInput,
        }"
        @toggle="state.confirmInput = !state.confirmInput"
      ></ItCheckbox>
      <div class="w-full border-b border-gray-400">
        <ItCheckbox
          class="py-6"
          :checkbox-item="{
            label: $t('assignment.confirmSubmitPerson'),
            value: 'value',
            checked: state.confirmPerson,
          }"
          @toggle="state.confirmPerson = !state.confirmPerson"
        ></ItCheckbox>
        <div class="flex flex-row items-center pb-6 pl-[49px]">
          <img
            alt="Notification icon"
            class="mr-2 h-[45px] min-w-[45px] rounded-full"
            :src="circleExpert.avatar_url"
          />
          <p class="text-base font-bold">
            {{ circleExpertName }}
          </p>
        </div>
        <!-- TODO: find way to find user that will do the corrections -->
      </div>
      <div class="flex flex-col space-x-2 pt-6 text-base sm:flex-row">
        <p>{{ $t("assignment.assessmentDocumentDisclaimer") }}</p>
        <a :href="props.assignment.evaluation_document_url" class="underline">
          {{ $t("assignment.showAssessmentDocument") }}
        </a>
      </div>
      <p class="pt-6">
        {{ $t("assignment.dueDateSubmission", { date: dueDate.format("DD.MM.YYYY") }) }}
      </p>
      <ItButton
        class="mt-6"
        variant="primary"
        size="large"
        :disabled="!state.confirmInput || !state.confirmPerson"
        @click="onSubmit"
      >
        <p>{{ $t("assignment.submitAssignment") }}</p>
      </ItButton>
    </div>
    <div v-else class="pt-6">
      <ItSuccessAlert :text="t('assignment.assignmentSubmitted')"></ItSuccessAlert>
      <p class="pt-6">
        {{
          $t("assignment.submissionNotificationDisclaimer", { name: circleExpertName })
        }}
      </p>
    </div>
  </div>
  <AssignmentSubmissionResponses
    :assignment="props.assignment"
    :assignment-completion-data="completionData"
    :allow-edit="completionStatus === 'IN_PROGRESS'"
    @edit-task="onEditTask"
  ></AssignmentSubmissionResponses>
</template>
