<template>
  <div class="mb-4 bg-white px-6 py-5">
    <h3 class="heading-3 mb-4 flex items-center gap-2">
      <it-icon-feedback-large class="h-16 w-16"></it-icon-feedback-large>
      <div>{{ $t("general.feedback", 2) }}</div>
    </h3>
    <ol v-if="feedbackSummary.length > 0">
      <ItRow v-for="feedbacks in feedbackSummary" :key="feedbacks.circle_id">
        <template #firstRow>
          <span class="text-bold">{{ $t("feedback.circleFeedback") }}</span>
        </template>
        <template #center>
          <div class="flex w-full justify-between">
            <div>Circle: {{ feedbacks.circle.title }}</div>
            <div>{{ $t("feedback.sentByUsers", feedbacks.count) }}</div>
          </div>
        </template>
        <template #link>
          <router-link
            :to="`${url}/cockpit/feedback/${feedbacks.circle_id}`"
            class="w-full text-right underline"
          >
            {{ $t("feedback.showDetails") }}
          </router-link>
        </template>
      </ItRow>
    </ol>
    <p v-else>{{ $t("feedback.noFeedbacks") }}</p>
  </div>
</template>

<script setup lang="ts">
import ItRow from "@/components/ui/ItRow.vue";
import { itGet } from "@/fetchHelpers";
import { onMounted, ref, watch } from "vue";

import type { Circle } from "@/services/circle";

interface FeedbackSummary {
  circle_id: number;
  count: number;
}

interface FeedbackDisplaySummary extends FeedbackSummary {
  circle: Circle;
}

function makeSummary(
  feedbackData: FeedbackSummary[],
  circles: Circle[],
  selectedCircles: string[]
) {
  const summary: FeedbackDisplaySummary[] = circles
    .filter((circle) => selectedCircles.includes(circle.translation_key))
    .reduce((acc: FeedbackDisplaySummary[], circle) => {
      const circleFeedbacks = feedbackData
        .filter((data) => data.circle_id === circle.id)
        .map((data) => Object.assign({}, data, { circle }));

      return acc.concat(circleFeedbacks);
    }, []);
  return summary;
}

const props = defineProps<{
  selctedCircles: string[];
  circles: Circle[];
  courseId: number;
  url: string;
}>();

const feedbackSummary = ref<FeedbackDisplaySummary[]>([]);
let feedbackData: FeedbackSummary[] = [];

onMounted(async () => {
  feedbackData = await itGet(`/api/core/feedback/${props.courseId}/summary`);
  feedbackSummary.value = makeSummary(
    feedbackData,
    props.circles,
    props.selctedCircles
  );
});

watch(
  () => props,
  () => {
    if (
      feedbackData.length > 0 &&
      props.circles.length > 0 &&
      props.selctedCircles.length > 0
    ) {
      feedbackSummary.value = makeSummary(
        feedbackData,
        props.circles,
        props.selctedCircles
      );
    }
  },
  { deep: true }
);
</script>
