/*
 * Copyright (C) 2025 by frePPLe bv
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
 */

<script setup lang="js">
import {computed, ref, onUnmounted, toRaw} from "vue";
import { useI18n } from 'vue-i18n';
import { useForecastsStore } from '@/stores/forecastsStore';
import ForecastSelectionCard from "@/components/ForecastSelectionCard.vue";
import CustomizeGrid from "@/components/CustomizeGrid.vue";
import { useBootstrapTooltips } from '@common/useBootstrapTooltips.js'

const { t: ttt, locale, availableLocales } = useI18n({
  useScope: 'global',  // This is crucial for reactivity
  inheritLocale: true
});

useBootstrapTooltips();

const store = useForecastsStore();
const dict =  {'I':  'item', 'L': 'location', 'C': 'customer'};

// to have these strings rendered in advance
const dictLabels = {'I': ttt('item'), 'L': ttt('location'), 'C': ttt('customer')};

// Add reactive references for resizing
const resizableContainer = ref(null);
const resizeHandle = ref(null);
const isResizing = ref(false);

const customizeGridRef = ref(null);

const currentMeasure = computed(() => {
  if (store.currentMeasure === null) {
    store.setCurrentMeasure(store.preferences.measure || 'nodata', false);
    return store.preferences.measure || 'nodata'
  }
  return store.currentMeasure;
});

const currentSequence = computed(() => {
  if (store.currentSequence === null) {
    store.setCurrentSequence(store.preferences.sequence || 'ILC', false);
    return store.preferences.sequence || 'ILC'
  }
  return store.currentSequence;
});

const currentRows = computed(() => {
  if (store.tableRows === null) {
    store.tableRows = store.preferences.rows || [];
    return store.preferences.rows
  }
  return store.tableRows;
});

const favoriteNames = ref(Object.keys(store.preferences?.favorites ?? {}) || []);

const currentHeight = computed(() => {
  if (store.dataRowHeight === null) {
    store.setCurrentHeight(store.preferences.height || 240);
    return store.preferences.height || 240
  }
  return store.dataRowHeight;
});

const sortedMeasureList = computed(() => {
  return Object.values(store.measures).sort((a, b) => {
    return a.label.localeCompare(b.label);
  });
});

const itemUnlocked = window.location.pathname.split('/editor/')[1] === "";

// Button event handlers
const showBucket = (event) => window.grid.showBucket();

const showImportDialog = (event) => {
  // event.preventDefault();

  if (typeof window.url_prefix !== 'undefined') {
    window.url = window.url_prefix + '/forecast/';
  }
  window.import_show('', undefined, true);
};

const showCustomizeGrid = (event) => {
  event.preventDefault();
  if (customizeGridRef.value) {
    customizeGridRef.value.showModal();
  }
};

const saveFavorite = (event) => {
  if (!('favorites' in store.preferences))
    store.preferences['favorites'] = {};
  const favName = document.querySelector("#favoritename").value;
  if (favName === '') return;

  store.preferences['favorites'][favName] = {
    'measure': store.currentMeasure,
    'sequence': store.currentSequence,
    'rows': toRaw(store.tableRows)
  };
  store.savePreferences();

  if (!favoriteNames.value.includes(favName)) {
    favoriteNames.value.push(favName);
  }
};

const openFavorite = (favName, event) => {
  if (!(favName in store.preferences.favorites)) return;
  const currentMeasure = store.preferences.favorites[favName]['measure'];
  const currentSequence = store.preferences.favorites[favName]['sequence'];
  const rows = store.preferences.favorites[favName]['rows'];
  store.setCurrentMeasure(currentMeasure);
  store.setCurrentSequence(currentSequence);
  store.tableRows = rows;
};

const removeFavorite = (favname, event) => {
  // event.preventDefault();
  delete store.preferences.favorites[favname];
  store.savePreferences();
  favoriteNames.value = favoriteNames.value.filter(f => f !== favname);
};

// Resize functionality - now updates store dataRowHeight
const startResize = (e) => {
  if (!resizableContainer.value) return;

  isResizing.value = true;
  const startY = e.clientY;
  const startHeight = currentHeight.value; // Use store height instead of container height

  const onMouseMove = (e) => {
    if (!isResizing.value) return;

    const deltaY = e.clientY - startY;
    const newHeight = startHeight + deltaY;

    // Set height constraints
    const minHeight = 150;
    const maxHeight = window.innerHeight * 0.8;

    if (newHeight >= minHeight && newHeight <= maxHeight) {
      // Update store dataRowHeight instead of local containerHeight
      store.setCurrentHeight(newHeight);
    }
  };

  const onMouseUp = () => {
    isResizing.value = false;
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
    document.body.style.userSelect = '';
    document.body.style.cursor = '';

    store.savePreferences();
  };

  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);
  document.body.style.userSelect = 'none';
  document.body.style.cursor = 'ns-resize';

  e.preventDefault();
};

// Cleanup on component unmount
onUnmounted(() => {
  document.body.style.userSelect = '';
  document.body.style.cursor = '';
});
</script>

<template>
  <div>
    <div class="row mb-1">
      <div class="col-auto">
        <div class="dropdown d-inline w-auto">
          <button id="selectseq" :title="ttt('Select panel sequence')" class="form-control d-inline w-auto dropdown-toggle text-capitalize" name="sequence" type="button" data-bs-toggle="dropdown" aria-expanded="false">
            {{ dictLabels[currentSequence[0]] }}{{(currentSequence).length > 1 ? "," : ""}}&nbsp;{{ dictLabels[currentSequence[1]] }}{{(currentSequence).length > 2 ? "," : ""}}&nbsp;{{ dictLabels[currentSequence[2]] }}&nbsp;&nbsp;<span class="caret"></span>
          </button>
          <ul class="dropdown-menu">
            <li>
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('ILC')">{{ ttt(dict['I']) }},&nbsp;{{ ttt(dict['L']) }},&nbsp;{{ ttt(dict['C']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('LIC')">{{ ttt(dict['L']) }},&nbsp;{{ ttt(dict['I']) }},&nbsp;{{ ttt(dict['C']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('CLI')">{{ ttt(dict['C']) }},&nbsp;{{ ttt(dict['L']) }},&nbsp;{{ ttt(dict['I']) }}</a>
            </li>
            <li>
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('ICL')">{{ ttt(dict['I']) }},&nbsp;{{ ttt(dict['C']) }},&nbsp;{{ ttt(dict['L']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('LCI')">{{ ttt(dict['L']) }},&nbsp;{{ ttt(dict['C']) }},&nbsp;{{ ttt(dict['I']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('CIL')">{{ ttt(dict['C']) }},&nbsp;{{ ttt(dict['I']) }},&nbsp;{{ ttt(dict['L']) }}</a>
            </li>
            <li>
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('IL')">{{ ttt(dict['I']) }},&nbsp;{{ ttt(dict['L']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('LI')">{{ ttt(dict['L']) }},&nbsp;{{ ttt(dict['I']) }}</a>
            </li>
            <li>
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('IC')">{{ ttt(dict['I']) }},&nbsp;{{ ttt(dict['C']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('CI')">{{ ttt(dict['C']) }},&nbsp;{{ ttt(dict['I']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('LC')">{{ ttt(dict['L']) }},&nbsp;{{ ttt(dict['C']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('CL')">{{ ttt(dict['C']) }},&nbsp;{{ ttt(dict['L']) }}</a>
            </li>
            <li>
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('I')">{{ ttt(dict['I']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('L')">{{ ttt(dict['L']) }}</a>
            </li>
            <li v-if="itemUnlocked">
              <a class="dropdown-item text-capitalize" href="#" v-on:click="store.setCurrentSequence('C')">{{ ttt(dict['C']) }}</a>
            </li>
          </ul>
        </div>
        &nbsp;&nbsp;
        <div class="dropdown d-inline w-auto ">
          <button id="selectmeasure" :title="ttt('Select panel measure')" class="dropdown-toggle form-control d-inline w-auto text-capitalize" name="measure" :value="measure" type="button" data-bs-toggle="dropdown" aria-expanded="false">
            {{ttt(store.measures[currentMeasure].label) }}&nbsp;&nbsp;<span class="caret"></span>
          </button>
          <ul class="dropdown-menu">
            <li v-for="m in sortedMeasureList" :key="m.name" >
              <a v-if="!m.computed" href="#" class="dropdown-item text-capitalize" @click="store.setCurrentMeasure(m.name)">{{ttt(m.label) }}</a>
            </li>
          </ul>
        </div>
      </div>

      <div id="toolicons" class="col-auto ms-auto hor-align-right ver-align-middle">
        <div>
          <button
              type="button"
              class="btn btn-sm btn-primary me-1"
              @click="showBucket"
              data-bs-toggle="tooltip"
              data-bs-placement="top"
              :data-bs-title="ttt('set time horizon')">
            <span class="fa fa-clock-o"></span>
          </button>
          <button
              type="button"
              class="btn btn-sm btn-primary me-1"
              data-bs-toggle="dropdown"
              aria-haspopup="true"
              aria-expanded="false">
            <span data-bs-toggle="tooltip" data-bs-placement="top" data-bs-html="true"
                 :data-bs-title="ttt('Bookmark your favorite report configurations')">
              <span class="fa fa-star"></span>
            </span>
          </button>
          <ul class="dropdown-menu dropdown-menu-end" id="favoritelist">
            <li v-for="favname in favoriteNames" :key="favname">
              <a class="dropdown-item" @click="openFavorite(favname, $event)">{{favname}}
                <div style="float:right"><span class="fa fa-trash-o" @click="removeFavorite(favname, $event)"></span></div>
              </a>
            </li>
            <li>
              <a class="dropdown-item d-flex" >
                <button
                    id="favoritesave"
                    @click="saveFavorite($event)"
                    type="button"
                    class="flex-fill btn btn-primary btn-sm me-1 text-capitalize aaa">{{ttt('save') }}</button>
                <input
                    class="form-control form-control-sm"
                    id="favoritename"
                    @input="checkFavorite"
                    type="text"
                    size="15">
              </a>
            </li>
          </ul>
          <button
              type="button"
              class="btn btn-sm d-none d-md-inline-block btn-primary me-1"
              @click="showImportDialog"
              data-bs-toggle="tooltip"
              data-bs-placement="top"
              :data-bs-title="ttt('Import CSV or Excel file')">
            <span id="csvimport" class="fa fa-arrow-up"></span>
          </button>
          <button
              type="button"
              class="btn btn-sm btn-primary me-1"
              @click="showCustomizeGrid"
              data-bs-toggle="tooltip"
              data-bs-placement="top"
              :data-bs-title="ttt('Customize')">
            <span class="fa fa-wrench"></span>
          </button>
        </div>
      </div>
    </div>

    <div class="row resizable" v-if="currentSequence && currentMeasure && currentHeight" id="data-row" style="max-height: 50vh; min-height: 150px;" :style="{'height': (currentHeight-31) + 'px'}"
          ref="resizableContainer">
      <div :class="{'col-sm-12': currentSequence.length === 1, 'col-sm-6': currentSequence.length === 2, 'col-sm-4': currentSequence.length === 3}" v-for="panel in currentSequence" :key="panel">
        <div>
          <ForecastSelectionCard v-if="panel" :panelid="panel" />
        </div>
      </div>
    </div>

    <div class="row">
      <div
        id="resize-handle"
        ref="resizeHandle"
        class="fa fa-bars handle col"
        style="display: block; text-align: center; clear: both; touch-action: none;"
        @mousedown="startResize"
      ></div>
    </div>
    <CustomizeGrid ref="customizeGridRef" />
  </div>
</template>
