import { Module } from "vuex";
import { RootState } from "..";

import {
  Comment,
  Ticket,
  TicketEmergencyState,
  TicketHistoryLine,
  TicketState,
} from "../../../../types";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";
import { ApiException } from "../../../../../../../../ChillMainBundle/Resources/public/types";
import { getSinceCreated } from "../../utils/utils";

export interface State {
  ticket: Ticket;
  action_icons: object;
}

export const moduleTicket: Module<State, RootState> = {
  state: () => ({
    ticket: {} as Ticket,
    action_icons: {
      add_person: "fa fa-user-plus",
      add_comment: "fa fa-comment",
      set_motive: "fa fa-paint-brush",
      addressees_state: "fa fa-paper-plane",
      persons_state: "fa fa-user",
      set_caller: "fa fa-phone",
      state_change: "",
      emergency_change: "",
    },
  }),
  getters: {
    isOpen(state) {
      return state.ticket.currentState === "open";
    },
    isEmergency(state) {
      return state.ticket.emergency == "yes";
    },
    isIncompleteTicket(state) {
      return (
        state.ticket.currentMotive === null ||
        !state.ticket.history.some((item) => item.event_type == "add_comment")
      );
    },
    getTicket(state) {
      state.ticket.history = state.ticket.history.sort((a, b) =>
        b.at.datetime.localeCompare(a.at.datetime),
      );
      return state.ticket;
    },
    getActionIcons(state) {
      return state.action_icons;
    },
    getSinceCreated: (state) => (currentTime: Date) => {
      if (!state.ticket.createdAt) {
        return "";
      }
      return getSinceCreated(state.ticket.createdAt.datetime, currentTime);
    },
    getTicketHistory: (state) => {
      return state.ticket.history;
    },
    getTicketHistoryComments: (state) => {
      return state.ticket.history.filter(
        (history) => history.event_type == "add_comment",
      );
    },
    getCurrentPersons(state) {
      return state.ticket.currentPersons;
    },
    getCaller: (state) => {
      return state.ticket.caller;
    },
  },

  mutations: {
    setTicket(state, ticket: Ticket) {
      state.ticket = ticket;
    },
    setTicketHistoryComment(state, ticketHistoryData: Comment) {
      const index = state.ticket.history.findIndex(
        (item: TicketHistoryLine) =>
          item.event_type == "add_comment" &&
          item.data.id === ticketHistoryData.id,
      );

      if (index !== -1) {
        state.ticket.history[index].data = ticketHistoryData;
      }
    },
  },
  actions: {
    async setTicketState({ commit, state }, ticketState: TicketState) {
      try {
        const result: Ticket = await makeFetch(
          "POST",
          `/api/1.0/ticket/ticket/${state.ticket.id}/${ticketState}`,
        );
        commit("setTicket", result as Ticket);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },

    async fetchTicket({ commit }, ticketId: number) {
      try {
        const ticket: Ticket = await makeFetch(
          "GET",
          `/api/1.0/ticket/ticket/${ticketId}`,
        );
        commit("setTicket", ticket);
      } catch (error) {
        console.error(
          "Erreur lors du chargement du ticket:",
          error as ApiException,
        );
        throw error;
      }
    },
    async setEmergency({ commit, state }, emergency: TicketEmergencyState) {
      try {
        const result: Ticket = await makeFetch(
          "POST",
          `/api/1.0/ticket/ticket/${state.ticket.id}/emergency/${emergency}`,
        );
        commit("setTicket", result as Ticket);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
  },
};
