import * as log from 'loglevel';

import {defineStore} from 'pinia'

import type {LearningContent, LearningUnit, LearningUnitQuestion} from '@/types'
import type {Circle} from '@/services/circle'
import {itGet, itPost} from '@/fetchHelpers';
import {useAppStore} from '@/stores/app';
import {useLearningPathStore} from '@/stores/learningPath';

export type CircleStoreState = {
  circle: Circle | undefined;
  currentLearningContent: LearningContent | undefined;
  currentSelfEvaluation: LearningUnit | undefined;
  page: 'INDEX' | 'OVERVIEW' | 'LEARNING_CONTENT' | 'SELF_EVALUATION';
}

export const useCircleStore = defineStore({
  id: 'circle',
  state: () => {
    return {
      circle: undefined,
      currentLearningContent: undefined,
      currentSelfEvaluation: undefined,
      page: 'INDEX',
    } as CircleStoreState;
  },
  getters: {
  },
  actions: {
    async loadCircle(slug: string) {
      this.circle = undefined;
      try {
        // const circleData = await itGet(`/learnpath/api/circle/${slug}/`);
        // this.circle = Circle.fromJson(circleData);
        // this.circle.parseCompletionData(completionData);
        const learningPathStore = useLearningPathStore();
        await learningPathStore.loadLearningPath('versicherungsvermittlerin');
        if (learningPathStore.learningPath) {
          this.circle = learningPathStore.learningPath.circles.find(circle => circle.slug === slug);
          if (this.circle) {
            const completionData = await itGet(`/api/completion/circle/${this.circle.translation_key}/`);
            this.circle.parseCompletionData(completionData);
          }
        }
        return Promise.resolve(this.circle)
      } catch (error) {
        log.error(error);
        return error
      }
    },
    async markCompletion(page: LearningContent | LearningUnitQuestion, flag = true) {
      try {
        page.completed = flag;
        const completionData = await itPost('/api/completion/circle/mark/', {
          page_key: page.translation_key,
          completed: page.completed,
        });
        if (this.circle) {
          this.circle.parseCompletionData(completionData);
        }
      } catch (error) {
        log.error(error);
        return error
      }
    },
    openLearningContent(learningContent: LearningContent) {
      this.currentLearningContent = learningContent;
      const appStore = useAppStore();
      appStore.showMainNavigationBar = false;
      this.page = 'LEARNING_CONTENT';
    },
    closeLearningContent() {
      this.currentLearningContent = undefined;
      const appStore = useAppStore();
      appStore.showMainNavigationBar = true;
      this.page = 'INDEX';
    },
    openSelfEvaluation(learningUnit: LearningUnit) {
      this.page = 'SELF_EVALUATION';
      const appStore = useAppStore();
      appStore.showMainNavigationBar = false;
      this.currentSelfEvaluation = learningUnit;
    },
    closeSelfEvaluation() {
      this.currentSelfEvaluation = undefined;
      const appStore = useAppStore();
      appStore.showMainNavigationBar = true;
      this.page = 'INDEX';
    },
    calcSelfEvaluationStatus(learningUnit: LearningUnit) {
      if (learningUnit.children.length > 0) {
        if (learningUnit.children.every((q) => q.completed)) {
          return true;
        }
        if (learningUnit.children.some((q) => q.completed !== undefined)) {
          return false;
        }
      }
      return undefined;
    },
    continueFromLearningContent() {
      if (this.currentLearningContent) {
        this.markCompletion(this.currentLearningContent, true);

        const nextLearningContent = this.currentLearningContent.nextLearningContent;
        const currentParent = this.currentLearningContent.parentLearningUnit;
        const nextParent = nextLearningContent?.parentLearningUnit;

        if (
          currentParent && currentParent.id &&
          currentParent.id !== nextParent?.id &&
          currentParent.children.length > 0
        ) {
          // go to self evaluation
          this.openSelfEvaluation(currentParent);
        } else if (this.currentLearningContent.nextLearningContent) {
          this.openLearningContent(this.currentLearningContent.nextLearningContent);
        } else {
          this.closeLearningContent();
        }
      } else {
        log.error('currentLearningContent is undefined');
      }
    },
    continueFromSelfEvaluation() {
      if (this.currentSelfEvaluation) {
        const nextContent = this.currentSelfEvaluation.learningContents[this.currentSelfEvaluation.learningContents.length - 1].nextLearningContent;
        if (nextContent) {
          this.openLearningContent(nextContent);
        } else {
          this.closeSelfEvaluation();
        }
      } else {
        log.error('currentSelfEvaluation is undefined');
      }
    }
  }
})
