<script setup lang="ts">
import ItSuccessAlert from "@/components/ui/ItSuccessAlert.vue";
import { useCurrentCourseSession } from "@/composables";
import { UPSERT_ASSIGNMENT_COMPLETION_MUTATION } from "@/graphql/mutations";
import {
  maxAssignmentPoints,
  pointsToGrade,
  userAssignmentPoints,
} from "@/services/assignmentService";
import type {
  Assignment,
  AssignmentCompletion,
  AssignmentEvaluationTask,
  CourseSessionUser,
} from "@/types";
import { useMutation } from "@urql/vue";
import dayjs, { Dayjs } from "dayjs";
import * as log from "loglevel";
import { computed, reactive } from "vue";

const props = defineProps<{
  assignmentUser: CourseSessionUser;
  assignment: Assignment;
  assignmentCompletion: AssignmentCompletion;
  showEvaluationUser?: boolean;
  dueDate?: Dayjs;
}>();

const emit = defineEmits(["editTask"]);

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

log.debug("EvaluationSummary setup");

const courseSession = useCurrentCourseSession();

const upsertAssignmentCompletionMutation = useMutation(
  UPSERT_ASSIGNMENT_COMPLETION_MUTATION
);

async function submitEvaluation() {
  // noinspection TypeScriptValidateTypes
  upsertAssignmentCompletionMutation.executeMutation({
    assignmentId: props.assignment.id.toString(),
    courseSessionId: courseSession.value.id.toString(),
    assignmentUserId: props.assignmentUser.user_id.toString(),
    completionStatus: "EVALUATION_SUBMITTED",
    completionDataString: JSON.stringify({}),
    evaluationGrade: grade.value ?? 1,
    evaluationPoints: userPoints.value,
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    id: props.assignmentCompletion?.id,
  });
  log.debug("submitEvaluation");
  state.showSuccessInfo = true;
}

function subTaskByPoints(task: AssignmentEvaluationTask, points = 0) {
  return task.value.sub_tasks.find((subTask) => subTask.value.points === points);
}

function evaluationForTask(task: AssignmentEvaluationTask) {
  const expertData = props.assignmentCompletion.completion_data[task.id]?.expert_data;
  if (!expertData) {
    return {
      points: 0,
      text: "",
    };
  }

  return expertData;
}

const maxPoints = computed(() => maxAssignmentPoints(props.assignment));
const userPoints = computed(() =>
  userAssignmentPoints(props.assignment, props.assignmentCompletion)
);
const grade = computed(() => {
  if (props.assignmentCompletion.completion_status === "EVALUATION_SUBMITTED") {
    return props.assignmentCompletion.evaluation_grade;
  }
  return pointsToGrade(userPoints.value, maxPoints.value);
});

const evaluationUser = computed(() => {
  if (props.assignmentCompletion.evaluation_user) {
    return (courseSession.value.users ?? []).find(
      (user) => user.user_id === Number(props.assignmentCompletion.evaluation_user)
    ) as CourseSessionUser;
  }

  return undefined;
});
</script>

<template>
  <!-- eslint-disable vue/no-v-html -->
  <div>
    <h3 v-if="evaluationUser && props.showEvaluationUser" class="mb-6">
      Bewertung von {{ evaluationUser.first_name }} {{ evaluationUser.last_name }}
    </h3>
    <h3 v-else class="mb-6">Bewertung Freigabe</h3>

    <section class="mb-6 border p-6">
      <div class="text-lg font-bold">Note: {{ grade }}</div>
      <div class="text-gray-900">
        Gesamtpunktezahl {{ userPoints }} / {{ maxPoints }}
      </div>

      <p class="my-4">
        Die Gesamtpunktzahl und die daraus resultierende Note wird auf Grund des
        hinterlegeten Beurteilungsinstrument berechnet.
      </p>

      <p class="my-4">
        <a
          :href="props.assignment.evaluation_document_url"
          class="link"
          target="_blank"
        >
          Beurteilungsinstrument anzeigen
        </a>
      </p>

      <div
        v-if="props.assignmentCompletion.completion_status === 'EVALUATION_SUBMITTED'"
      >
        Freigabetermin:
        {{
          dayjs(props.assignmentCompletion.evaluation_submitted_at).format("DD.MM.YYYY")
        }}
        um
        {{ dayjs(props.assignmentCompletion.evaluation_submitted_at).format("HH.mm") }}
        Uhr
      </div>
      <div v-else>
        <button class="btn-primary text-large" @click="submitEvaluation()">
          Bewertung freigeben
        </button>
      </div>

      <div v-if="state.showSuccessInfo" class="mt-4">
        <ItSuccessAlert
          :text="`Deine Bewertung für ${props.assignmentUser.first_name} ${props.assignmentUser.last_name} wurde freigegeben.`"
        ></ItSuccessAlert>
      </div>
    </section>

    <section>
      <div v-for="(task, index) in props.assignment.evaluation_tasks" :key="task.id">
        <article class="border-t py-4">
          <div class="flex flex-row justify-between">
            <div class="mb-4 text-gray-900">
              Bewertungskriterium {{ index + 1 }}: {{ task.value.title }}
            </div>
            <div
              v-if="
                props.assignmentCompletion.completion_status !== 'EVALUATION_SUBMITTED'
              "
            >
              <button
                class="link pl-2text-sm whitespace-nowrap"
                @click="emit('editTask', task)"
              >
                {{ $t("assignment.edit") }}
              </button>
            </div>
          </div>

          <div
            class="default-wagtail-rich-text mb-2 font-bold"
            v-html="task.value.description"
          ></div>

          <section class="mb-4">
            <div
              v-html="
                subTaskByPoints(task, evaluationForTask(task).points)?.value.title
              "
            ></div>
            <p
              class="default-wagtail-rich-text"
              v-html="
                subTaskByPoints(task, evaluationForTask(task).points)?.value.description
              "
            ></p>
            <div class="text-sm text-gray-800">
              {{ evaluationForTask(task).points }} Punkte
            </div>
          </section>

          <div>
            <span class="font-bold">Begründung:</span>
            {{ evaluationForTask(task).text }}
          </div>
        </article>
      </div>
    </section>
  </div>
</template>

<style lang="scss" scoped></style>
