<template>
  <div
    class="card my-2 bg-light"
    v-for="history_line in filteredHistoryLines"
    :key="history.indexOf(history_line)"
  >
    <div class="card-header">
      <div class="history-header row align-items-center gx-0">
        <div class="col d-flex align-items-center">
          <i :class="`${actionIcons[history_line.event_type]} me-1`"></i>
          <span class="fw-bold">{{ explainSentence(history_line) }}</span>
          <state-component
            :new_state="history_line.data.new_state"
            v-if="history_line.event_type == 'state_change'"
          />
          <emergency-component
            v-else-if="history_line.event_type == 'emergency_change'"
            :new_emergency="history_line.data.new_emergency"
          />
        </div>
        <div class="col-auto d-flex justify-content-end align-items-center">
          <span class="badge-user d-flex">
            <user-render-box-badge :user="history_line.by" />
          </span>
          <span class="fst-italic mx-2 d-flex">
            {{ formatDate(history_line.at) }}
          </span>
        </div>
      </div>
    </div>
    <div class="card-body row" v-if="displayBody(history_line)">
      <person-component
        :entities="history_line.data.persons"
        v-if="history_line.event_type == 'persons_state'"
      />
      <person-component
        :entities="
          history_line.data.new_caller
            ? ([history_line.data.new_caller] as Person[] | Thirdparty[])
            : []
        "
        v-else-if="history_line.event_type == 'set_caller'"
      />
      <motive-component
        :motiveHistory="history_line.data"
        v-else-if="history_line.event_type == 'set_motive'"
      />
      <comment-component
        :commentHistory="history_line.data"
        v-else-if="history_line.event_type == 'add_comment'"
      />
      <addressee-component
        :addressees="history_line.data.addressees"
        v-else-if="history_line.event_type == 'addressees_state'"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import { useStore } from "vuex";

// Types
import { DateTime } from "../../../../../../../ChillMainBundle/Resources/public/types";
import { TicketHistoryLine } from "../../../types";
import { Person } from "ChillPersonAssets/types";
import { Thirdparty } from "src/Bundle/ChillThirdPartyBundle/Resources/public/types";

// Components
import PersonComponent from "../../TicketApp/components/Person/PersonComponent.vue";
import MotiveComponent from "../../TicketApp/components/Motive/MotiveComponent.vue";
import CommentComponent from "../../TicketApp/components/Comment/CommentComponent.vue";
import AddresseeComponent from "../../TicketApp/components/Addressee/AddresseeComponent.vue";
import StateComponent from "../../TicketApp/components/State/StateComponent.vue";
import EmergencyComponent from "../../TicketApp/components/Emergency/EmergencyComponent.vue";

import UserRenderBoxBadge from "ChillMainAssets/vuejs/_components/Entity/UserRenderBoxBadge.vue";

// Utils
import { ISOToDatetime } from "../../../../../../../ChillMainBundle/Resources/public/chill/js/date";

// Translations
import {
  trans,
  CHILL_TICKET_TICKET_HISTORY_ADD_COMMENT,
  CHILL_TICKET_TICKET_HISTORY_ADDRESSEES_STATE,
  CHILL_TICKET_TICKET_HISTORY_PERSONS_STATE,
  CHILL_TICKET_TICKET_HISTORY_SET_MOTIVE,
  CHILL_TICKET_TICKET_HISTORY_CREATE_TICKET,
  CHILL_TICKET_TICKET_HISTORY_STATE_CHANGE,
  CHILL_TICKET_TICKET_HISTORY_EMERGENCY_CHANGE,
  CHILL_TICKET_TICKET_HISTORY_SET_CALLER,
} from "translator";

const props = defineProps<{ history?: TicketHistoryLine[] }>();
const history = props.history ?? [];
const store = useStore();

const actionIcons = ref<Record<string, string>>(store.getters.getActionIcons);
const removedCommentIds = ref<number[]>(store.getters.getRemovedCommentIds);

const filteredHistoryLines = computed(() =>
  history.filter(
    (line: TicketHistoryLine) =>
      line.event_type !== "add_person" &&
      !(
        line.event_type == "add_comment" &&
        line.data.deleted &&
        !removedCommentIds.value.includes(line.data.id)
      ),
  ),
);

function explainSentence(history: TicketHistoryLine): string {
  switch (history.event_type) {
    case "add_comment":
      return trans(CHILL_TICKET_TICKET_HISTORY_ADD_COMMENT);
    case "addressees_state":
      return trans(CHILL_TICKET_TICKET_HISTORY_ADDRESSEES_STATE, {
        count: history.data.addressees.length,
      });
    case "persons_state":
      return trans(CHILL_TICKET_TICKET_HISTORY_PERSONS_STATE, {
        count: history.data.persons.length,
      });
    case "set_motive":
      return trans(CHILL_TICKET_TICKET_HISTORY_SET_MOTIVE);
    case "create_ticket":
      return trans(CHILL_TICKET_TICKET_HISTORY_CREATE_TICKET);
    case "state_change":
      return trans(CHILL_TICKET_TICKET_HISTORY_STATE_CHANGE);
    case "emergency_change":
      return trans(CHILL_TICKET_TICKET_HISTORY_EMERGENCY_CHANGE);
    case "set_caller":
      return trans(CHILL_TICKET_TICKET_HISTORY_SET_CALLER, {
        id: history.data.new_caller?.id ?? "null",
      });
    default:
      return "";
  }
}

function displayBody(history_line: TicketHistoryLine): boolean {
  // Dont display body if no entities or if is change of state, emergency
  const data = Object.values(history_line.data)[0];
  if (data == null) {
    return false;
  } else if (Array.isArray(data) && data.length === 0) {
    return false;
  } else if (
    ["state_change", "emergency_change"].includes(history_line.event_type)
  ) {
    return false;
  }
  return true;
}

function formatDate(d: DateTime): string {
  const date = ISOToDatetime(d.datetime);

  if (date === null) {
    return "";
  }

  const month = date.toLocaleString("default", { month: "long" });
  return `${date.getDate()} ${month} ${date.getFullYear()}, ${date.toLocaleTimeString()}`;
}
</script>
