<template>
  <div class="row">
    <div class="col-12">
      <comment-editor v-model="content" />
    </div>
    <div class="col-12" v-if="motive">
      <div
        class="input-group mb-2"
        v-for="(supplementaryComments, index) in motive.supplementaryComments"
        :key="index"
      >
        <div class="input-group-prepend d-flex align-items-center px-1">
          <span class="badge rounded-pill bg-chill-red">
            {{ supplementaryComments.label }}
          </span>
        </div>

        <input
          type="text"
          v-model="supplementaryCommentsInput[index]"
          class="form-control"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, computed, ComputedRef } from "vue";

// Components
import CommentEditor from "ChillMainAssets/vuejs/_components/CommentEditor/CommentEditor.vue";

// Types
import { Motive, MotiveWithParent } from "../../../../types";

// Utils
import { StoredObject } from "ChillDocStoreAssets/types";
import { useStore } from "vuex";

const props = defineProps<{
  modelValue?: string;
  motive?: MotiveWithParent | null;
}>();

const store = useStore();
const supplementaryCommentsInput = reactive<string[]>([]);

const emit = defineEmits<{
  "update:modelValue": [value: string];
  "show-peloton-modal": [storedObjects: StoredObject[]];
}>();

const content = ref(props.modelValue);
const motive: ComputedRef<Motive | null> = computed(() =>
  store.getters.getMotiveById(props.motive?.id),
);

function aggregateSupplementaryComments() {
  let supplementaryText = " \n\n ";
  if (props.motive && motive.value && motive.value.supplementaryComments) {
    motive.value.supplementaryComments.forEach(
      (item: { label: string }, index: number) => {
        if (supplementaryCommentsInput[index]) {
          supplementaryText +=
            `**${item.label}**:  ${supplementaryCommentsInput[index]}` +
            " \n\n ";
        }
      },
    );
  }
  return (content.value || "") + supplementaryText;
}

watch(
  supplementaryCommentsInput,
  () => {
    emit("update:modelValue", aggregateSupplementaryComments());
  },
  { deep: true },
);

watch(content, () => {
  emit("update:modelValue", aggregateSupplementaryComments());
});
</script>

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