<template>
  <div>

    <h2 class="page-header">My calculations</h2>


    <div class="calculation-list-container">

      <the-calculation-search @execute-search="updateFilter"/>

      <!-- Header -->
      <div class="calculation-list-header">
        <div>
          <checkbox @checkbox-changed="updateCheckBoxes" :checked="overallCheck"
                    :indeterminate="overallIndeterminate"></checkbox>
        </div>
        <div>Material</div>
        <div>Supplier</div>
        <div>Status</div>
        <div>Action</div>
      </div>
      <transition name="list-container" mode="out-in">
        <div v-if="premiseStore.showData">
          <calculation-list-item v-for="premise in premiseStore.premises" :key="premise.id" :id="premise.id"
                                 :checked="premiseStore.isChecked(premise.id)"
                                 @update-checkbox="updateCheckbox"
                                 @update-pagination="updatePagination"></calculation-list-item>
        </div>
        <div v-else-if="premiseStore.showEmpty" class="empty-container">
          <span class="space-around">No Calculations found.</span>
        </div>

        <div v-else class="spinner-container">
          <spinner class="space-around"></spinner>
        </div>
      </transition>
      <pagination :page="pagination.page" :page-count="pagination.pageCount"
                  :total-count="pagination.totalCount" @page-change="updatePage"></pagination>
    </div>

    <modal-dialog :title="modal.title" :state="modal.state" :message="modal.message" :accept-text="modal.acceptText"
                  :deny-text="modal.denyText" :dismiss-text="modal.dismissText"
                  @click="handleModalAction"></modal-dialog>
    <list-edit :show="showListEdit" :select-count="premiseStore.selectedIds.length"
               @action="handleMultiselectAction"></list-edit>


  </div>


</template>


<script>

import TheCalculationSearch from "@/components/layout/calculation/TheCalculationSearch.vue";
import BasicBadge from "@/components/UI/BasicBadge.vue";
import IconButton from "@/components/UI/IconButton.vue";
import Flag from "@/components/UI/Flag.vue";
import NotificationBar from "@/components/UI/NotificationBar.vue";
import Checkbox from "@/components/UI/Checkbox.vue";
import CalculationListItem from "@/components/layout/calculation/CalculationListItem.vue";
import {usePremiseStore} from "@/store/premise.js";
import {mapStores} from "pinia";
import Spinner from "@/components/UI/Spinner.vue";
import ListEdit from "@/components/UI/ListEdit.vue";
import {UrlSafeBase64} from "@/common.js";
import Pagination from "@/components/UI/Pagination.vue";
import ModalDialog from "@/components/UI/ModalDialog.vue";
import modal from "@/components/UI/Modal.vue";

export default {
  name: "Calculation",
  components: {
    ModalDialog,
    Pagination,
    ListEdit,
    Spinner,
    CalculationListItem, Checkbox, NotificationBar, IconButton, BasicBadge, TheCalculationSearch, Flag
  },
  computed: {
    ...mapStores(usePremiseStore),
    showListEdit() {
      return this.premiseStore.globallySomeChecked;
    }
  },
  data() {
    return {
      selectedStatus: null,
      modal: {
        title: "",
        message: "",
        acceptText: "OK",
        denyText: null,
        dismissText: "Cancel",
        state: false,
        action: "",
      },
      overallCheck: false,
      overallIndeterminate: false,
      pagination: {
        page: 1,
        pageCount: 1,
        totalCount: 0
      },
      query: {
        searchTerm: null,
        page: 1,
        pageSize: 10,
        archived: false,
        done: false,
        draft: true,
      }
    }
  },
  async created() {
    this.premiseStore.resetSelectedIds();
    await this.executeSearch();
  },
  methods: {
    async handleModalAction(action) {
      if (action === 'dismiss') {
        this.modal.state = false;
        return;
      }

      if (action === 'accept' && this.modal.action === "delete") {
        await this.executeMultiselectAction(this.modal.action, this.selectedStatus.draft)
      }

      if (action === 'accept' && this.modal.action === "archive") {
        await this.executeMultiselectAction(this.modal.action, this.selectedStatus.completed)
      }

      if (this.modal.action === "edit") {
        if (action === 'deny')
          await this.executeMultiselectAction(this.modal.action, this.selectedStatus.draft);
        else {
          const ids = await this.premiseStore.createDrafts([...this.selectedStatus.archived, ...this.selectedStatus.completed]);
          await this.executeMultiselectAction(this.modal.action, [...this.selectedStatus.draft, ...ids]);
        }
      }

      this.modal.state = false;
    },
    async executeMultiselectAction(action, ids) {
      if (action === "delete") {
        if (ids.length !== 0) {
          await this.premiseStore.deletePremisses(ids);
          this.premiseStore.resetSelectedIds();
          this.updateOverallCheckBox();
          this.updatePagination();
        }
      } else if (action === "edit") {
        if (ids.length === 1) {
          this.$router.push({name: "edit", params: {id: new UrlSafeBase64().encodeIds([ids[0]])}});
        } else if (ids.length !== 0) {
          this.$router.push({name: "bulk", params: {ids: new UrlSafeBase64().encodeIds(ids)}});
        }
      } else if (action === "archive") {
        if (ids.length !== 0) {
          await this.premiseStore.archivePremisses(ids);
          this.premiseStore.resetSelectedIds();
          this.updateOverallCheckBox();
          this.updatePagination();
        }
      }
    },
    async handleMultiselectAction(action) {
      this.selectedStatus = await this.premiseStore.resolveStatus();

      if (action === "delete") {

        if (0 === this.selectedStatus.draft.length) {
          this.modal.title = "Unable to delete calculations";
          this.modal.message = `All of the ${this.premiseStore.selectedIds.length} selected calculations are already completed or archived and can no longer be deleted.`;
          this.modal.action = "delete";
          this.modal.state = true;
          this.modal.acceptText = null;
          this.modal.denyText = null;
          this.modal.dismissText = "OK";
        } else if (0 < (this.selectedStatus.completed.length + this.selectedStatus.archived.length)) {
          this.modal.title = "Delete calculations";
          this.modal.message = `${(this.selectedStatus.completed.length + this.selectedStatus.archived.length)} of the ${this.premiseStore.selectedIds.length} selected calculations are already completed or archived and can no longer be deleted. Do you still want to delete the remaining ${this.selectedStatus.draft.length} calculations?`;
          this.modal.action = "delete";
          this.modal.state = true;
          this.modal.acceptText = "Delete";
          this.modal.denyText = null;
          this.modal.dismissText = "Cancel";
        } else
          this.executeMultiselectAction(action, this.selectedStatus.draft);


      } else if (action === "edit") {

        if (0 === this.selectedStatus.draft.length) {
          this.modal.title = "Edit calculations";
          this.modal.message = `All of the ${this.premiseStore.selectedIds.length} selected calculations are already completed or archived and can no longer be edited. Would you like to create new drafts based on the data from the existing calculations?`;
          this.modal.action = "edit";
          this.modal.state = true;
          this.modal.acceptText = "Create new drafts & edit";
          this.modal.denyText = null;
          this.modal.dismissText = "Cancel";
        } else if (0 < (this.selectedStatus.completed.length + this.selectedStatus.archived.length)) {
          this.modal.title = "Edit calculations";
          this.modal.message = `${(this.selectedStatus.completed.length + this.selectedStatus.archived.length)} of the ${this.premiseStore.selectedIds.length} selected calculations are already completed or archived and can no longer be edited. Would you like to create new drafts based on the data from the existing calculations, or continue the operation without these calculations?`;
          this.modal.action = "edit";
          this.modal.state = true;
          this.modal.acceptText = "Create new drafts & edit";
          this.modal.denyText = "Edit drafts only";
          this.modal.dismissText = "Cancel";
        } else
          this.executeMultiselectAction(action, this.selectedStatus.draft);

      } else if (action === "archive") {

        if (0 === this.selectedStatus.completed.length) {
          this.modal.title = "Unable to archive calculations";
          this.modal.message = `All of the ${this.premiseStore.selectedIds.length} selected calculations are in draft status or already archived and cannot be archived.`;
          this.modal.action = "archive";
          this.modal.state = true;
          this.modal.acceptText = null;
          this.modal.denyText = null;
          this.modal.dismissText = "OK";
        } else if (0 < (this.selectedStatus.draft.length + this.selectedStatus.archived.length)) {
          this.modal.title = "Archive calculations";
          this.modal.message = `${(this.selectedStatus.draft.length + this.selectedStatus.archived.length)} of the ${this.premiseStore.selectedIds.length} selected calculations are in draft status or already archived and cannot be archived. Do you still want to archive the remaining ${this.selectedStatus.completed.length} calculations?`;
          this.modal.action = "archive";
          this.modal.state = true;
          this.modal.acceptText = "Archive";
          this.modal.denyText = null;
          this.modal.dismissText = "Cancel";
        } else
          this.executeMultiselectAction(action, this.selectedStatus.completed);

      } else if (action === "deselect") {
        this.selectedStatus = null;
        this.premiseStore.resetSelectedIds();
        this.updateOverallCheckBox();
      }
    },
    updatePagination(resetPage = true) {
      if(resetPage) {
        this.updatePage(1);
      }
      this.pagination = this.premiseStore.pagination;
    },
    updateCheckbox(data) {
      this.premiseStore.setChecked(data.id, data.checked);
      this.updateOverallCheckBox();
    },
    updateCheckBoxes(checked) {
      this.premiseStore.premises.forEach(p => {
        this.premiseStore.setChecked(p.id, checked);
      })
      this.updateOverallCheckBox();
    },
    updateOverallCheckBox() {
      this.overallCheck = this.premiseStore.allChecked;

      if (!this.overallCheck)
        this.overallIndeterminate = this.premiseStore.someChecked;
    },
    async updatePage(page) {
      this.query.page = page;
      await this.executeSearch();
    },
    async updateFilter(query) {

      if (this.query.archived !== query.archived ||
          this.query.done !== query.done ||
          this.query.draft !== query.draft ||
          this.query.searchTerm !== query.searchTerm) {
        this.query.page = 1;
      }

      this.query.searchTerm = query.searchTerm;
      this.query.archived = query.archived;
      this.query.done = query.done;
      this.query.draft = query.draft;

      await this.executeSearch();
    },
    async executeSearch() {

      await this.premiseStore.setQuery(this.query);
      this.updatePagination(false);
      this.updateOverallCheckBox();
    }
  }
}
</script>

<style scoped>

.space-around {
  margin: 3rem;
}

/* Container Animation */
.list-container-enter-active, .list-container-leave-active {
  transition: all 0.3s ease;
}

.list-container-enter-from, .list-container-leave-to {
  opacity: 0;
}

.list-edit-enter-active {
  transition: all 0.1s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.list-edit-leave-active {
  transition: all 0.1s ease-in;
}

.list-edit-enter-from {
  transform: translateY(-30px) scale(0.8);
  opacity: 0;
}

.list-edit-leave-to {
  transform: translateY(-30px) scale(0.8);
  opacity: 0;
}

.calculation-list-edit-container {
  display: flex;
  justify-content: center;
}

.spinner-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.6rem;
}

.errorCode {
  font-weight: 600;
}

.calculation-search-box {
  margin-top: 3rem;
  display: grid;
  gap: 0.8rem;
  grid-template-columns: 5rem 1fr 1fr 1fr 1fr;
}

.calculation-search-header {
  font-weight: 400;
  font-size: 1.4rem;
  color: #6B869C;
  text-transform: uppercase;
}

.calculation-list-container {
  background: white;
  border-radius: 1.2rem;
  box-shadow: 0 0.4rem 0.6rem -0.1rem rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-top: 3rem;
  margin-bottom: 3rem;

}

.calculation-list-header {
  display: grid;
  grid-template-columns: 6rem 1fr 2fr 14rem 10rem;
  gap: 1.6rem;
  padding: 1.6rem;
  background-color: #ffffff;
  border-bottom: 1px solid rgba(107, 134, 156, 0.2);
  font-weight: 500;
  font-size: 1.4rem;
  color: #6B869C;
  text-transform: uppercase;
  letter-spacing: 0.08rem;
}

@media (max-width: 768px) {
  .calculation-list-header {
    display: none;
    grid-template-columns: 1fr;
    gap: 0.8rem;
  }
}


</style>