<template>
  <div>

    <div class="header-container">
      <div>
        <h2 class="page-header"> My calculations</h2>
      </div>
      <div class="header-help-container">
        <icon-button v-if="useHelpStore().enableHelp" icon="info"
                     @click="useHelpStore().activateHelp('dashboard')"></icon-button>
      </div>

    </div>

    <h2 class="page-sub-header">{{ greeting }}</h2>


    <h3 class="sub-header">Status</h3>

    <the-dashboard></the-dashboard>

    <h3 class="sub-header">Drafts</h3>
    <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>Created at</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";
import {useActiveUserStore} from "@/store/activeuser.js";
import TheDashboard from "@/components/layout/calculation/TheDashboard.vue";
import Box from "@/components/UI/Box.vue";
import {useHelpStore} from "@/store/help.js";

export default {
  name: "Calculation",
  components: {
    Box,
    TheDashboard,
    ModalDialog,
    Pagination,
    ListEdit,
    Spinner,
    CalculationListItem, Checkbox, NotificationBar, IconButton, BasicBadge, TheCalculationSearch, Flag
  },
  computed: {
    ...mapStores(usePremiseStore, useActiveUserStore),
    showListEdit() {
      return this.premiseStore.globallySomeChecked;
    },
    greeting() {
      const now = new Date();
      const hour = now.getHours();

      // Get day of year as seed for consistent random selection throughout the day
      const dayOfYear = Math.floor((now - new Date(now.getFullYear(), 0, 0)) / 86400000);

      let greetings = [];

      // Morning: 5-12
      if (hour >= 5 && hour < 12) {
        greetings = [
          `Good morning, ${this.username}`,
          `Morning, ${this.username}!`,
          `Good morning, ${this.username}. Ready to calculate?`,
          `Morning ${this.username}, what's on the agenda today?`
        ];
      }
      // Afternoon: 12-18
      else if (hour >= 12 && hour < 18) {
        greetings = [
          `Good afternoon, ${this.username}`,
          `Hi ${this.username}, welcome back`,
          `Afternoon, ${this.username}!`,
          `Hello ${this.username}, let's continue`,
          `Hi ${this.username}, ready to work?`
        ];
      }
      // Evening: 18-22
      else if (hour >= 18 && hour < 22) {
        greetings = [
          `Good evening, ${this.username}`,
          `Evening, ${this.username}!`,
          `Hi ${this.username}, still working hard?`,
          `Good evening, ${this.username}, almost done for today?`
        ];
      }
      // Night: 22-5
      else {
        greetings = [
          `Working late, ${this.username}?`,
          `Hi ${this.username}, burning the midnight oil?`,
          `Hello ${this.username}`,
          `Still here, ${this.username}?`,
          `Hi ${this.username}, don't stay up too late`
        ];
      }

      // Use day of year as seed for consistent selection
      const index = dayOfYear % greetings.length;
      return greetings[index];
    },
    username() {
      return this.activeUserStore.username;
    }
  },
  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: {
    useHelpStore,
    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>

.header-help-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 1.6rem;
}

.header-container {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  gap: 1.6rem;
}

.page-header {
  font-weight: normal;
  margin-bottom: 0;
  font-size: 2.4rem;
  color: #002F54;
}

.page-sub-header {
  font-weight: normal;
  font-size: 1.8rem;
  color: #6B869C;
  margin-bottom: 2.4rem;
}


.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 20rem 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>