<template>
  <div>
    <div class="row justify-content-end" v-if="!isEvaluationSelector">
      <div class="col-md-6 col-sm-10" v-if="selectedAcpw">
        <ul class="list-suggest remove-items">
          <li>
            <span @click="selectedAcpw = null" class="chill-denomination">{{
              selectedAcpw?.socialAction?.title.fr
            }}</span>
          </li>
        </ul>
      </div>
    </div>

    <ul v-if="!showModal" class="record_actions">
      <li>
        <a class="btn btn-sm btn-create mt-3" @click="openModal">
          {{ trans(ACPW_DUPLICATE_SELECT_ACCOMPANYING_PERIOD_WORK) }}
        </a>
      </li>
    </ul>

    <teleport to="body">
      <modal
        v-if="showModal"
        @close="closeModal"
        modal-dialog-class="modal-dialog-scrollable modal-xl"
      >
        <template #header>
          <h3>
            {{ getModalTitle() }}
          </h3>
        </template>

        <template #body>
          <accompanying-period-work-list
            v-if="evaluations.length === 0"
            :accompanying-period-works="accompanyingPeriodWorks"
            v-model:selectedAcpw="selectedAcpw"
          />
          <accompanying-period-work-evaluation-list
            v-if="evaluations.length > 0"
            :evaluations="evaluations"
            v-model:selectedEvaluation="selectedEvaluation"
          />
        </template>

        <template #footer>
          <button type="button" class="btn btn-save" @click="confirmSelection">
            {{ trans(CONFIRM) }}
          </button>
        </template>
      </modal>
    </teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import Modal from "ChillMainAssets/vuejs/_components/Modal.vue";
import AccompanyingPeriodWorkList from "./AccompanyingPeriodWorkList.vue";
import { AccompanyingPeriodWork } from "../../../types";
import {
  trans,
  ACPW_DUPLICATE_SELECT_ACCOMPANYING_PERIOD_WORK,
  ACPW_DUPLICATE_SELECT_AN_EVALUATION,
  CONFIRM,
} from "translator";
import { fetchResults } from "ChillMainAssets/lib/api/apiMethods";
import AccompanyingPeriodWorkEvaluationList from "ChillPersonAssets/vuejs/_components/AccompanyingPeriodWorkSelector/AccompanyingPeriodWorkEvaluationList.vue";
import { AccompanyingPeriodWorkEvaluation } from "../../../types";

const selectedAcpw = ref<AccompanyingPeriodWork | null>(null);
const selectedEvaluation = ref<AccompanyingPeriodWorkEvaluation | null>(null);
const showModal = ref(false);
const accompanyingPeriodWorks = ref<AccompanyingPeriodWork[]>([]);
const evaluations = ref<AccompanyingPeriodWorkEvaluation[]>([]);

const props = defineProps<{
  accompanyingPeriodId: string;
  isEvaluationSelector: boolean;
  ignoreAccompanyingPeriodWorkIds: number[];
}>();

const emit = defineEmits<{
  pickWork: [payload: { work: AccompanyingPeriodWork | null }];
  closeModal: [];
  "update:selectedEvaluation": [evaluation: AccompanyingPeriodWorkEvaluation];
}>();

const getModalTitle = () =>
  evaluations.value.length > 0
    ? trans(ACPW_DUPLICATE_SELECT_AN_EVALUATION)
    : trans(ACPW_DUPLICATE_SELECT_ACCOMPANYING_PERIOD_WORK);

onMounted(() => {
  if (props.accompanyingPeriodId) {
    getAccompanyingPeriodWorks(parseInt(props.accompanyingPeriodId));
  } else {
    console.error("No accompanyingperiod id was given");
  }

  showModal.value = true;
});

const getAccompanyingPeriodWorks = async (periodId: number) => {
  const url = `/api/1.0/person/accompanying-course/${periodId}/works.json`;

  const accompanyingPeriodWorksFetched =
    await fetchResults<AccompanyingPeriodWork>(url);
  if (props.isEvaluationSelector) {
    accompanyingPeriodWorks.value = accompanyingPeriodWorksFetched.filter(
      (acpw: AccompanyingPeriodWork) =>
        acpw.accompanyingPeriodWorkEvaluations.length > 0 &&
        typeof acpw.id !== "undefined" &&
        !props.ignoreAccompanyingPeriodWorkIds.includes(acpw.id),
    );
  } else {
    accompanyingPeriodWorks.value = accompanyingPeriodWorksFetched;
  }
};

watch(selectedAcpw, (newValue) => {
  const inputField = document.getElementById(
    "find_accompanying_period_work_acpw",
  ) as HTMLInputElement;
  if (inputField) {
    inputField.value = String(newValue?.id || "");
  }

  /*  if (!props.isEvaluationSelector) {
    console.log("Emitting from watch:", { work: newValue });
    emit("pickWork", { work: newValue });
  }*/
});

const openModal = () => {
  showModal.value = true;
};
const closeModal = () => {
  showModal.value = false;
  selectedEvaluation.value = null;
  // selectedAcpw.value = null;
  emit("closeModal");
};
const confirmSelection = () => {
  selectedAcpw.value = selectedAcpw.value;
  console.log("selectedAcpw", selectedAcpw.value);

  if (!props.isEvaluationSelector) {
    if (selectedAcpw.value) {
      // only emit if something is actually selected!emit("pickWork", { work: selectedAcpw.value });
      closeModal();
    }
    // optionally show some error or warning if not selected
    return;
  }

  if (selectedAcpw.value && props.isEvaluationSelector) {
    evaluations.value = selectedAcpw.value.accompanyingPeriodWorkEvaluations;
  }

  if (selectedEvaluation.value && props.isEvaluationSelector) {
    // console.log('evaluation log in modal', selectedEvaluation.value)
    emit("update:selectedEvaluation", selectedEvaluation.value);
    closeModal();
  }
};
</script>
