<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-12 mb-4">
        <ticket-filter-list-component
          :resultCount="resultCount"
          :available-persons="availablePersons"
          :available-motives="availableMotives"
          :ticket-filter-params="ticketFilterParams"
          @filters-changed="handleFiltersChanged"
        />
      </div>
      <div class="col-12">
        <!-- Loading state -->
        <div
          v-if="isLoading"
          class="d-flex justify-content-center align-items-center"
          style="height: 200px"
        >
          <div class="text-center">
            <div class="spinner-border mb-3" role="status">
              <span class="visually-hidden">{{
                trans(CHILL_TICKET_LIST_LOADING_TICKET)
              }}</span>
            </div>
            <div class="text-muted">
              {{ trans(CHILL_TICKET_LIST_LOADING_TICKET) }}
            </div>
          </div>
        </div>

        <!-- Ticket list -->
        <ticket-list-component
          v-else
          :tickets="ticketList"
          :hasMoreTickets="pagination.next !== null"
          @fetchNextPage="fetchNextPage"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useStore } from "vuex";

// Types
import { TicketSimple, Motive, TicketFilterParams } from "../../types";
import type { Person } from "ChillPersonAssets/types";

// Components
import TicketListComponent from "./components/TicketListComponent.vue";
import TicketFilterListComponent from "./components/TicketFilterListComponent.vue";
import { Pagination } from "ChillMainAssets/lib/api/apiMethods";

// Translations
import { trans, CHILL_TICKET_LIST_LOADING_TICKET } from "translator";

const store = useStore();
const ticketFilterParams = window.ticketFilterParams
  ? window.ticketFilterParams
  : null;

const isLoading = ref(false);
const ticketList = computed(
  () => store.getters.getTicketList as TicketSimple[],
);
const resultCount = computed(() => store.getters.getCount as number);
const pagination = computed(() => store.getters.getPagination as Pagination);
const availablePersons = ref<Person[]>([]);
const availableMotives = computed(() => store.getters.getMotives as Motive[]);

const handleFiltersChanged = async (filters: TicketFilterParams) => {
  isLoading.value = true;
  try {
    await store.dispatch("fetchTicketList", filters);
  } finally {
    isLoading.value = false;
  }
};

const fetchNextPage = async () => {
  if (pagination.value.next) {
    await store.dispatch("fetchTicketListByUrl", pagination.value.next);
  }
};

onMounted(async () => {
  isLoading.value = true;
  const filters: TicketFilterParams = {
    byPerson: ticketFilterParams?.byPerson
      ? ticketFilterParams.byPerson.map((person) => person.id)
      : [],
    byCreator: ticketFilterParams?.byCreator
      ? ticketFilterParams.byCreator.map((creator) => creator.id)
      : [],
    byAddressee: ticketFilterParams?.byAddressee
      ? ticketFilterParams.byAddressee.map((addressee) => addressee.id)
      : [],
    byCurrentState: ticketFilterParams?.byCurrentState ?? ["open"],
    byCurrentStateEmergency: ticketFilterParams?.byCurrentStateEmergency ?? [],
    byMotives: ticketFilterParams?.byMotives
      ? ticketFilterParams.byMotives.map((motive) => motive.id)
      : [],
    byCreatedAfter: ticketFilterParams?.byCreatedAfter ?? "",
    byCreatedBefore: ticketFilterParams?.byCreatedBefore ?? "",
    byResponseTimeExceeded: ticketFilterParams?.byResponseTimeExceeded
      ? "true"
      : "",
    byAddresseeToMe: ticketFilterParams?.byAddresseeToMe ?? false,
    byTicketId: ticketFilterParams?.byTicketId ?? null,
  };
  try {
    await store.dispatch("fetchTicketList", filters);
    store.dispatch("getCurrentUser");
    store.dispatch("fetchMotives");
  } finally {
    isLoading.value = false;
  }
});
</script>

<style lang="scss" scoped>
.container-fluid {
  padding: 1rem;
}
</style>
