<template>
  <teleport to="#actionToolbar">
    <div class="footer-ticket-details" v-if="activeTab">
      <div class="tab-content p-2">
        <button
          type="button"
          class="btn btn-link p-0"
          style="
            position: absolute;
            right: 0.5rem;
            font-size: 2rem;
            line-height: 1;
            color: #888;
            text-decoration: none;
          "
          @click="closeAllActions"
          aria-label="Fermer"
          title="Fermer"
        >
          <span aria-hidden="true">&times;</span>
        </button>
        <div v-if="activeTabTitle">
          <label class="col-form-label">
            {{ activeTabTitle }}
          </label>
        </div>

        <form class="p-2" @submit.prevent="submitAction">
          <comment-editor-component
            v-model="content"
            :motive="motive"
            v-if="activeTab === 'add_comment'"
          />
          <addressee-selector-component
            v-model="addressees"
            :suggested="userGroups"
            v-if="activeTab === 'addressees_state'"
          />

          <motive-selector-component
            v-model="motive"
            :motives="motives"
            open-direction="top"
            v-if="activeTab === 'set_motive'"
          />
          <div v-if="activeTab === 'persons_state'">
            <div class="row">
              <label class="col col-form-label">
                {{ trans(CHILL_TICKET_TICKET_SET_PERSONS_TITLE_CALLER) }}
              </label>
              <label class="col col-form-label">
                {{ trans(CHILL_TICKET_TICKET_SET_PERSONS_TITLE_PERSON) }}
              </label>
            </div>
            <div class="row">
              <div class="col">
                <persons-selector-component
                  v-model="caller"
                  :suggested="[]"
                  :multiple="false"
                  :types="['person', 'thirdparty']"
                  :label="trans(CHILL_TICKET_TICKET_SET_PERSONS_CALLER_LABEL)"
                />
              </div>
              <div class="col">
                <persons-selector-component
                  v-model="persons"
                  :suggested="suggestedPersons"
                  :multiple="true"
                  :types="['person']"
                  :label="trans(CHILL_TICKET_TICKET_SET_PERSONS_USER_LABEL)"
                />
              </div>
            </div>
          </div>

          <ul class="record_actions sticky-form-buttons">
            <li>
              <button class="btn btn-save" type="submit">
                {{ trans(CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_SAVE) }}
              </button>
            </li>
          </ul>
        </form>
      </div>
    </div>
    <div class="footer-ticket-main">
      <div class="d-flex w-100">
        <ul class="nav nav-tabs flex-grow-1 justify-content-start">
          <li v-if="hasReturnPath" class="nav-item p-2 go-back">
            <a :href="returnPath" class="btn btn-cancel">
              <span class="hide-on-sm">
                {{ trans(CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_CANCEL) }}
              </span>
            </a>
          </li>
        </ul>
        <ul class="nav nav-tabs flex-grow-1 justify-content-center">
          <template v-for="btn in actionButtons" :key="btn.key">
            <li class="nav-item p-2">
              <button
                type="button"
                :class="`btn ${activeTab === btn.key ? 'btn-primary' : 'btn-light'}`"
                @click="
                  activeTab === btn.key
                    ? (activeTab = '')
                    : (activeTab = btn.key)
                "
                :disabled="btn.disabled.value"
              >
                <i :class="actionIcons[btn.key]" />
                <span class="hide-on-sm ms-2">{{ trans(btn.label) }}</span>
              </button>
            </li>
          </template>
        </ul>
        <ul class="nav nav-tabs flex-grow-1 justify-content-end">
          <li class="nav-item p-2">
            <button
              type="button"
              class="btn bg-chill-green text-white"
              @click="isOpen ? closeTicket() : reopenTicket()"
            >
              <i :class="isOpen ? 'fa fa-lock' : 'fa fa-unlock'"></i>
              <span class="hide-on-sm ms-2">
                {{
                  isOpen
                    ? trans(CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_CLOSE)
                    : trans(CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_REOPEN)
                }}
              </span>
            </button>
          </li>
        </ul>
      </div>
    </div>
  </teleport>
</template>

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

// Component
import MotiveSelectorComponent from "./Motive/MotiveSelectorComponent.vue";
import AddresseeSelectorComponent from "./Addressee/AddresseeSelectorComponent.vue";
import CommentEditorComponent from "./Comment/CommentEditorComponent.vue";
import PersonsSelectorComponent from "./Person/PersonsSelectorComponent.vue";

// Translations
import {
  trans,
  CHILL_TICKET_TICKET_ADD_ADDRESSEE_TITLE,
  CHILL_TICKET_TICKET_ADD_ADDRESSEE_ERROR,
  CHILL_TICKET_TICKET_ADD_ADDRESSEE_SUCCESS,
  CHILL_TICKET_TICKET_ADD_COMMENT_TITLE,
  CHILL_TICKET_TICKET_ADD_COMMENT_ERROR,
  CHILL_TICKET_TICKET_ADD_COMMENT_SUCCESS,
  CHILL_TICKET_TICKET_SET_MOTIVE_TITLE,
  CHILL_TICKET_TICKET_SET_MOTIVE_ERROR,
  CHILL_TICKET_TICKET_SET_MOTIVE_SUCCESS,
  CHILL_TICKET_TICKET_SET_PERSONS_TITLE_PERSON,
  CHILL_TICKET_TICKET_SET_PERSONS_TITLE_CALLER,
  CHILL_TICKET_TICKET_SET_PERSONS_TITLE,
  CHILL_TICKET_TICKET_SET_PERSONS_SUCCESS,
  CHILL_TICKET_TICKET_SET_PERSONS_USER_LABEL,
  CHILL_TICKET_TICKET_SET_PERSONS_CALLER_LABEL,
  CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_SAVE,
  CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_CLOSE,
  CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_CLOSE_SUCCESS,
  CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_CLOSE_ERROR,
  CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_REOPEN,
  CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_REOPEN_SUCCESS,
  CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_REOPEN_ERROR,
  CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_CANCEL,
  CHILL_TICKET_TICKET_SET_PERSONS_ERROR,
} from "translator";

// Types
import {
  UserGroup,
  UserGroupOrUser,
} from "../../../../../../../ChillMainBundle/Resources/public/types";
import { Comment, Motive, MotiveWithParent, Ticket } from "../../../types";
import { Person } from "ChillPersonAssets/types";

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

const activeTab = ref("" as string);
const actionIcons = ref(store.getters.getActionIcons);

const activeTabTitle = computed((): string => {
  switch (activeTab.value) {
    case "add_comment":
      return trans(CHILL_TICKET_TICKET_ADD_COMMENT_TITLE);
    case "set_motive":
      return trans(CHILL_TICKET_TICKET_SET_MOTIVE_TITLE);
    case "addressees_state":
      return trans(CHILL_TICKET_TICKET_ADD_ADDRESSEE_TITLE);
    default:
      return "";
  }
});

const actionButtons = [
  {
    key: "set_motive",
    label: CHILL_TICKET_TICKET_SET_MOTIVE_TITLE,
    icon: computed(() => actionIcons.value["set_motive"]),
    disabled: computed(() => !isOpen.value),
  },
  {
    key: "add_comment",
    label: CHILL_TICKET_TICKET_ADD_COMMENT_TITLE,
    icon: computed(() => actionIcons.value["add_comment"]),
    disabled: computed(() => !isOpen.value),
  },
  {
    key: "addressees_state",
    label: CHILL_TICKET_TICKET_ADD_ADDRESSEE_TITLE,
    icon: computed(() => actionIcons.value["addressees_state"]),
    disabled: computed(() => !isOpen.value),
  },
  {
    key: "persons_state",
    label: CHILL_TICKET_TICKET_SET_PERSONS_TITLE,
    icon: computed(() => actionIcons.value["persons_state"]),
    disabled: computed(() => !isOpen.value),
  },
];

const ticket = computed(() => store.getters.getTicket as Ticket);
const isOpen = computed(() => store.getters.isOpen);
const motives = computed(() => store.getters.getMotives as Motive[]);
const userGroups = computed(() => store.getters.getUserGroups as UserGroup[]);
const suggestedPersons = computed(() => store.getters.getPersons as Person[]);

const hasReturnPath = computed((): boolean => {
  const params = new URL(document.location.toString()).searchParams;
  return params.has("returnPath");
});

const returnPath = computed((): string => {
  const params = new URL(document.location.toString()).searchParams;
  const returnPath = params.get("returnPath");

  if (null === returnPath) {
    throw new Error(
      "there isn't any returnPath, please check the existence before",
    );
  }

  return returnPath;
});

const motive = ref(ticket.value.currentMotive as MotiveWithParent | null);
const content = ref("" as Comment["content"]);
const addressees = ref(ticket.value.currentAddressees as UserGroupOrUser[]);
const persons = ref(ticket.value.currentPersons as Person[]);
const caller = ref(ticket.value.caller as Person);

async function submitAction() {
  switch (activeTab.value) {
    case "add_comment":
      if (!content.value) {
        toast.error(trans(CHILL_TICKET_TICKET_ADD_COMMENT_ERROR));
      } else {
        await store.dispatch("createComment", content.value);
        content.value = "";
        activeTab.value = "";
        toast.success(trans(CHILL_TICKET_TICKET_ADD_COMMENT_SUCCESS));
      }
      break;
    case "set_motive":
      if (!motive.value) {
        toast.error(trans(CHILL_TICKET_TICKET_SET_MOTIVE_ERROR));
      } else {
        await store.dispatch("createMotive", motive.value);
        activeTab.value = "";
        toast.success(trans(CHILL_TICKET_TICKET_SET_MOTIVE_SUCCESS));
      }
      break;
    case "addressees_state":
      if (addressees.value.length) {
        try {
          await store.dispatch(
            "setAddressees",
            addressees.value as UserGroupOrUser[],
          );
          activeTab.value = "";
          toast.success(trans(CHILL_TICKET_TICKET_ADD_ADDRESSEE_SUCCESS));
        } catch (error) {
          console.error(trans(CHILL_TICKET_TICKET_ADD_ADDRESSEE_ERROR), error);
          toast.error(trans(CHILL_TICKET_TICKET_ADD_ADDRESSEE_ERROR));
        }
      } else {
        await store.dispatch("setAddressees", [] as UserGroupOrUser[]);
        toast.success(trans(CHILL_TICKET_TICKET_ADD_ADDRESSEE_SUCCESS));
      }
      break;
    case "persons_state":
      if (persons.value.length) {
        await store.dispatch("setPersons", persons.value);
        try {
          await store.dispatch("fetchTicketList", {
            byPerson: persons.value.map((person) => person.id),
          });
          activeTab.value = "";
          toast.success(trans(CHILL_TICKET_TICKET_SET_PERSONS_SUCCESS));
        } catch (error) {
          console.error(trans(CHILL_TICKET_TICKET_SET_PERSONS_ERROR), error);
          toast.error(trans(CHILL_TICKET_TICKET_SET_PERSONS_ERROR));
        }
      } else {
        store.dispatch("setPersons", [] as Person[]);
        toast.success(trans(CHILL_TICKET_TICKET_SET_PERSONS_SUCCESS));
      }
      break;
  }
}

async function closeTicket() {
  try {
    await store.dispatch("setTicketState", "close");
    closeAllActions();
    toast.success(trans(CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_CLOSE_SUCCESS));
  } catch (error) {
    console.error(error);
    toast.success(trans(CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_CLOSE_ERROR));
  }
}

async function reopenTicket() {
  try {
    await store.dispatch("setTicketState", "open");
    toast.success(trans(CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_REOPEN_SUCCESS));
  } catch (error) {
    console.error(error);
    toast.error(trans(CHILL_TICKET_TICKET_ACTIONS_TOOLBAR_REOPEN_ERROR));
  }
}

function closeAllActions() {
  activeTab.value = "";
}

watch(caller, async (newCaller) => {
  await store.dispatch("setCaller", newCaller);
  await store.dispatch("getSuggestedPersons");
});
</script>

<style lang="scss" scoped>
.go-back {
  margin-right: auto;
}

.sticky-form-buttons {
  margin-top: 0px;
  background: none;
}
div.footer-ticket-main {
  background: none repeat scroll 0 0 #cabb9f;
}

div.footer-ticket-details {
  background: none repeat scroll 0 0 #efe2ca;
}
</style>
