<script setup lang="ts">
import ItCheckbox from "@/components/ui/ItCheckbox.vue";
import { useCircleStore } from "@/stores/circle";
import type {
  CourseCompletionStatus,
  LearningContent,
  LearningSequence,
} from "@/types";
import { humanizeDuration } from "@/utils/humanizeDuration";
import _ from "lodash";
import { computed } from "vue";
import LearningContentBadge from "./LearningContentTypeBadge.vue";

interface Props {
  learningSequence: LearningSequence;
  readonly?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  readonly: false,
});

const circleStore = useCircleStore();

function toggleCompleted(learningContent: LearningContent) {
  let completionStatus: CourseCompletionStatus = "success";
  if (learningContent.completion_status === "success") {
    completionStatus = "fail";
  }
  circleStore.markCompletion(learningContent, completionStatus);
}

const someFinished = computed(() => {
  if (props.learningSequence && circleStore.circle) {
    return circleStore.circle.someFinishedInLearningSequence(
      props.learningSequence.translation_key
    );
  }

  return false;
});

const allFinished = computed(() => {
  if (props.learningSequence && circleStore.circle) {
    return circleStore.circle.allFinishedInLearningSequence(
      props.learningSequence.translation_key
    );
  }

  return false;
});

const continueTranslationKeyTuple = computed(() => {
  if (props.learningSequence && circleStore.circle) {
    const lastFinished = _.findLast(
      circleStore.circle.flatLearningContents,
      (learningContent) => {
        return learningContent.completion_status === "success";
      }
    );

    if (!lastFinished) {
      // must be the first
      return [circleStore.circle.flatLearningContents[0].translation_key, true];
    }

    if (lastFinished && lastFinished.nextLearningContent) {
      return [lastFinished.nextLearningContent.translation_key, false];
    }
  }

  return "";
});

const learningSequenceBorderClass = computed(() => {
  let result: string[] = [];
  if (props.learningSequence && circleStore.circle) {
    if (allFinished.value) {
      result = ["border-l-4", "border-l-green-500"];
    } else if (someFinished.value) {
      result = ["border-l-4", "border-l-sky-500"];
    } else {
      result = ["border-l-gray-500"];
    }
  }

  return result;
});
</script>

<template>
  <div :id="learningSequence.slug" class="mb-8 learning-sequence">
    <div class="flex items-center gap-4 mb-2 text-blue-900">
      <component :is="learningSequence.icon" />
      <h3 class="text-large font-semibold">
        {{ learningSequence.title }}
      </h3>
      <div>{{ humanizeDuration(learningSequence.minutes) }}</div>
    </div>

    <ol class="bg-white px-4 lg:px-6 border" :class="learningSequenceBorderClass">
      <li
        v-for="learningUnit in learningSequence.learningUnits"
        :id="learningUnit.slug"
        :key="learningUnit.id"
        class="pt-3 lg:pt-6"
      >
        <div v-if="learningUnit.title" class="pb-3 lg:pg-6 flex gap-4 text-blue-900">
          <div class="font-semibold">{{ learningUnit.title }}</div>
          <div class="whitespace-nowrap">
            {{ humanizeDuration(learningUnit.minutes) }}
          </div>
        </div>
        <ol>
          <li
            v-for="learningContent in learningUnit.learningContents"
            :key="learningContent.id"
            class="flex gap-4 pb-3 lg:pb-6 items-center"
          >
            <div v-if="props.readonly">
              <it-icon-check
                v-if="learningContent.completion_status === 'success'"
                class="block w-8 h-8"
              ></it-icon-check>
              <div v-else class="w-8 h-8"></div>
            </div>
            <ItCheckbox
              v-else
              :checked="learningContent.completion_status === 'success'"
              :data-cy="`${learningContent.slug}-checkbox`"
              @toggle="toggleCompleted(learningContent)"
            />
            <div class="flex-auto pt-1 sm:pt-0">
              <span class="flex gap-4 items-center xl:h-10">
                <div v-if="props.readonly" class="w-full sm:w-auto text-left">
                  {{ learningContent.title }}
                </div>
                <button
                  v-else
                  class="cursor-pointer w-full sm:w-auto text-left"
                  :data-cy="`${learningContent.slug}`"
                  @click.stop="circleStore.openLearningContent(learningContent)"
                >
                  {{ learningContent.title }}
                </button>

                <div
                  class="flex items-center gap-4 flex-col justify-between md:flex-row sm:grow lg:flex-col xl:flex-row"
                >
                  <button
                    v-if="
                      learningContent.translation_key ===
                        continueTranslationKeyTuple[0] && !props.readonly
                    "
                    class="btn-blue order-1 sm:order-none"
                    data-cy="ls-continue-button"
                    @click.stop="circleStore.openLearningContent(learningContent)"
                  >
                    <span
                      v-if="continueTranslationKeyTuple[1]"
                      class="whitespace-nowrap"
                    >
                      {{ $t("general.start") }}
                    </span>
                    <span v-else class="whitespace-nowrap">
                      {{ $t("general.nextStep") }}
                    </span>
                  </button>
                  <div class="hidden sm:block"></div>
                  <div class="w-full sm:w-auto">
                    <LearningContentBadge
                      :learning-content-type="learningContent.contents[0].type"
                    />
                  </div>
                </div>
              </span>
            </div>
          </li>
        </ol>

        <div
          v-if="learningUnit.children.length"
          :class="{ 'cursor-pointer': !props.readonly }"
          :data-cy="`${learningUnit.slug}`"
          @click="!props.readonly && circleStore.openSelfEvaluation(learningUnit)"
        >
          <div
            v-if="circleStore.calcSelfEvaluationStatus(learningUnit) === 'success'"
            class="flex items-center gap-4 pb-3 lg:pb-6 self-evaluation-success"
          >
            <it-icon-smiley-happy class="w-8 h-8 flex-none" data-cy="success" />
            <div>Selbsteinschätzung: Ich kann das.</div>
          </div>
          <div
            v-else-if="circleStore.calcSelfEvaluationStatus(learningUnit) === 'fail'"
            class="flex items-center gap-4 pb-3 lg:pb-6 self-evaluation-fail"
          >
            <it-icon-smiley-thinking class="w-8 h-8 flex-none" data-cy="fail" />
            <div>Selbsteinschätzung: Muss ich nochmals anschauen</div>
          </div>
          <div
            v-else
            class="flex items-center gap-4 pb-3 lg:pb-6 self-evaluation-unknown"
          >
            <it-icon-smiley-neutral class="w-8 h-8 flex-none" data-cy="unknown" />
            <div>Selbsteinschätzung</div>
          </div>
        </div>

        <hr v-if="!learningUnit.last" class="-mx-4 text-gray-500" />
      </li>
    </ol>
  </div>
</template>

<style scoped></style>
