<template>
  <banner-component :ticket="ticket" />
  <div class="container-xxl pt-1" style="padding-bottom: 55px" v-if="!loading">
    <div class="row">
      <div class="col">
        <label class="form-label pe-2" for="showAllHistory">
          {{ trans(CHILL_TICKET_LIST_SHOW_ALL_HISTORY) }}
        </label>
        <toggle-component v-model="showAllHistory" id="showAllHistory" />
      </div>
      <div class="col d-flex justify-content-end">
        <previous-tickets-component :key="refreshKey" />
      </div>
    </div>
    <ticket-history-list-component
      :history="ticketHistory"
      :key="ticketHistory.length"
    />
  </div>

  <div v-else class="text-center p-4">
    <div class="spinner-border" role="status">
      <span class="visually-hidden">
        {{ trans(CHILL_TICKET_LIST_LOADING_TICKET_DETAILS) }}
      </span>
    </div>
    <div>{{ trans(CHILL_TICKET_LIST_LOADING_TICKET_DETAILS) }}</div>
  </div>
  <action-toolbar-component :key="refreshKey" v-if="!loading" />
  <Modal
    v-if="showTicketInitFormModal"
    :show="showTicketInitFormModal"
    :modal-dialog-class="modalDialogClass"
    @close="closeModal"
  >
    <template #header>
      <h3 class="modal-title">
        {{ trans(CHILL_TICKET_TICKET_INIT_FORM_TITLE) }}
      </h3>
    </template>

    <template #body>
      <ticket-init-form-component
        v-model="ticketForm"
        :ticket="ticket"
        :motives="motives"
        :suggested-persons="suggestedPersons"
        @submit="handleFormSubmit"
      />
    </template>
    <template #footer>
      <button class="btn btn-primary" @click="handleFormSubmit">
        {{ trans(CHILL_TICKET_TICKET_INIT_FORM_SUBMIT) }}
      </button>
    </template>
  </Modal>
</template>

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

// Types
import { Ticket, Motive, TicketInitForm } from "../../types";
import { Person } from "ChillPersonAssets/types";

// Components
import Modal from "../../../../../../ChillMainBundle/Resources/public/vuejs/_components/Modal.vue";
import PreviousTicketsComponent from "./components/PreviousTicketsComponent.vue";
import TicketHistoryListComponent from "../TicketList/components/TicketHistoryListComponent.vue";
import ActionToolbarComponent from "./components/ActionToolbarComponent.vue";
import BannerComponent from "./components/BannerComponent.vue";
import TicketInitFormComponent from "./components/TicketInitFormComponent.vue";
import ToggleComponent from "../TicketList/components/ToggleComponent.vue";

// Translations
import {
  trans,
  CHILL_TICKET_TICKET_INIT_FORM_SUBMIT,
  CHILL_TICKET_TICKET_INIT_FORM_TITLE,
  CHILL_TICKET_TICKET_INIT_FORM_SUCCESS,
  CHILL_TICKET_TICKET_INIT_FORM_ERROR,
  CHILL_TICKET_TICKET_INIT_FORM_WARNING,
  CHILL_TICKET_LIST_LOADING_TICKET_DETAILS,
  CHILL_TICKET_LIST_SHOW_ALL_HISTORY,
} from "translator";

const store = useStore();
const toast = useToast();

store.commit("setTicket", JSON.parse(window.initialTicket) as Ticket);
const showAllHistory = ref(false);
const ticket = computed(() => store.getters.getTicket as Ticket);
const ticketHistory = computed(() =>
  showAllHistory.value
    ? store.getters.getTicketHistory
    : store.getters.getTicketHistoryComments,
);
const motives = computed(() => store.getters.getMotives as Motive[]);
const suggestedPersons = computed(() => store.getters.getPersons as Person[]);
const showTicketInitFormModal = ref(false);
const loading = ref(true);
const refreshKey = ref(0);

// ticketForm réactif pour v-model
const ticketForm = ref({
  content: "",
  addressees: ticket.value?.currentAddressees,
  motive: ticket.value?.currentMotive,
  persons: ticket.value?.currentPersons,
  caller: ticket.value?.caller,
  emergency: ticket.value?.emergency,
} as TicketInitForm);

const modalDialogClass = ref(
  window.innerWidth < 990 ? "modal-fullscreen" : "modal-lg",
);

function updateModalClass() {
  modalDialogClass.value =
    window.innerWidth < 990 ? "modal-fullscreen" : "modal-lg";
}
window.addEventListener("resize", updateModalClass);

async function handleFormSubmit() {
  try {
    if (!ticketForm.value.motive || ticketForm.value.content.trim() === "") {
      toast.warning(trans(CHILL_TICKET_TICKET_INIT_FORM_WARNING));
      return;
    }
    if (ticketForm.value.motive) {
      await store.dispatch("createMotive", ticketForm.value.motive);
    }
    if (ticketForm.value.content.trim() !== "") {
      await store.dispatch("createComment", ticketForm.value.content);
    }

    // Ne pas mettre à jour emergency si le motif force l'état d'urgence
    if (
      ticketForm.value.motive &&
      !ticketForm.value.motive.makeTicketEmergency
    ) {
      await store.dispatch("setEmergency", ticketForm.value.emergency);
    }

    await store.dispatch("setAddressees", ticketForm.value.addressees);
    await store.dispatch("setPersons", ticketForm.value.persons);

    // Forcer le rafraîchissement des composants
    refreshKey.value++;

    toast.success(trans(CHILL_TICKET_TICKET_INIT_FORM_SUCCESS));
    closeModal();
  } catch (error) {
    toast.error(
      (error as string) || trans(CHILL_TICKET_TICKET_INIT_FORM_ERROR),
    );
  }
}

function closeModal() {
  showTicketInitFormModal.value = false;
}

onMounted(() => {
  try {
    store.dispatch("getCurrentUser");
    store.dispatch("fetchMotives");
    store.dispatch("fetchUserGroups");
    store.dispatch("fetchUsers");
    store.dispatch("getSuggestedPersons");
    showTicketInitFormModal.value = store.getters.isIncompleteTicket;
  } catch (error) {
    toast.error(error as string);
  } finally {
    loading.value = false;
  }
});

onUnmounted(() => {
  window.removeEventListener("resize", updateModalClass);
});
</script>

<style lang="scss" scoped>
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  font-size: 2rem;
  color: #333;
}
.form-label {
  font-weight: bold;
}
</style>
