/*
 * 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 } from "vue";
import { useI18n } from 'vue-i18n';
import { useOperationplansStore } from '@/stores/operationplansStore.js';
import { numberFormat, dateTimeFormat, adminEscape } from "@common/utils.js";

const urlPrefix = computed(() => window.url_prefix || '');

const { t: ttt } = useI18n({
  useScope: 'global',
  inheritLocale: true
});

const store = useOperationplansStore();

const props = defineProps({
  widget: {
    type: Array,
    default: () => []
  }
});

const isCollapsed = computed(() => props.widget[1]?.collapsed ?? false);

const hasFlowplans = computed(() => {
  const op = store.operationplan;
  return op && op.flowplans && Array.isArray(op.flowplans) && op.flowplans.length > 0;
});

const flowplans = computed(() => {
  return store.operationplan.flowplans || [];
});

// Vue version of selectAlternateItem
function selectAlternateItem(flowplan, newItem) {
  const currentItem = flowplan.buffer?.item;

  if (newItem !== currentItem) {
    // Find and update the flowplan in the store
    const operationplan = store.operationplan;
    if (operationplan && operationplan.flowplans) {
      const flowToUpdate = operationplan.flowplans.find(flow =>
          flow.buffer?.item === currentItem
      );

      if (flowToUpdate) {
        // Update the assigned item
        flowToUpdate.buffer.item = newItem;

        // Update the grid if it exists
        updateGrid(currentItem, newItem);

        // Enable save/undo buttons
        enableSaveUndoButtons();
      }
    }
  }
}

function updateGrid(currentItem, newItem) {
  // Check if grid exists (maintaining compatibility with existing jqGrid)
  const gridElement = document.querySelector("#grid");
  if (!gridElement) return;

  const grid = window.jQuery(gridElement);
  const selrow = grid.jqGrid('getGridParam', 'selarrrow');
  const colmodel = grid.jqGrid('getGridParam', 'colModel')?.find(i => i.name === "material");

  if (!colmodel || !selrow) return;

  const cell = grid.jqGrid('getCell', selrow, 'material');

  if (colmodel.formatter === 'detail' && cell === currentItem) {
    grid.jqGrid("setCell", selrow, "material", newItem, "dirty-cell");
    grid.jqGrid("setRowData", selrow, false, "edited");
  }
  else if (colmodel.formatter === 'listdetail') {
    const items = [];
    const operationplan = store.operationplan;
    if (operationplan && operationplan.flowplans) {
      operationplan.flowplans.forEach(flowplan => {
        items.push([flowplan.buffer?.item, flowplan.quantity]);
      });
    }
    grid.jqGrid("setCell", selrow, "material", items, "dirty-cell");
    grid.jqGrid("setRowData", selrow, false, "edited");
  }
}

function enableSaveUndoButtons() {
  const saveBtn = document.querySelector("#save");
  const undoBtn = document.querySelector("#undo");

  if (saveBtn) {
    saveBtn.classList.remove("btn-primary");
    saveBtn.classList.add("btn-danger");
    saveBtn.disabled = false;
  }

  if (undoBtn) {
    undoBtn.classList.remove("btn-primary");
    undoBtn.classList.add("btn-danger");
    undoBtn.disabled = false;
  }
}

</script>

<template>
  <div>
    <div
        class="card-header d-flex align-items-center"
        data-bs-toggle="collapse"
        data-bs-target="#widget_bufferspanel"
        aria-expanded="false"
        aria-controls="widget_bufferspanel"
    >
      <h5 class="card-title text-capitalize fs-5 me-auto">
        {{ ttt('items') }}
      </h5>
      <span class="fa fa-arrows align-middle w-auto widget-handle"></span>
    </div>

    <div
      id="widget_bufferspanel"
      class="card-body collapse"
      :class="{ 'show': !isCollapsed }"
      style="max-height: 50vh; overflow-y: auto; overflow-x: hidden;"
    >
      <table class="table table-sm table-hover table-borderless" style="table-layout: auto; width: 100%;">
        <thead>
        <tr v-if="store.operationplan.type === 'DO'">
          <th style="width: 100%; max-width: 0; overflow: hidden; text-overflow: ellipsis"><b class="text-capitalize">{{ ttt('item') }}</b></th>
          <th class="w-auto text-center px-3"><b class="text-capitalize text-center">{{ ttt('location') }}</b></th>
          <th class="w-auto text-center px-3"><b class="text-capitalize text-center">{{ ttt('quantity') }}</b></th>
          <th class="w-auto text-center px-3"><b class="text-capitalize text-center">{{ ttt('onhand') }}</b></th>
          <th class="w-auto text-center px-3"><b class="text-capitalize text-center">{{ ttt('date') }}</b></th>
        </tr>
        <tr v-else>
          <th style="width: 100%; max-width: 0; overflow: hidden; text-overflow: ellipsis"><b class="text-capitalize">{{ ttt('item') }}</b></th>
          <th class="w-auto text-center px-3"><b class="text-capitalize">{{ ttt('quantity') }}</b></th>
          <th class="w-auto text-center px-3"><b class="text-capitalize">{{ ttt('onhand') }}</b></th>
          <th class="w-auto text-center px-3"><b class="text-capitalize">{{ ttt('date') }}</b></th>
        </tr>
        </thead>
        <tbody>
        <tr v-if="!hasFlowplans">
          <td colspan="5">{{ ttt('no movements') }}</td>
        </tr>

        <tr
          v-for="(flowplan, index) in flowplans"
          :key="index"
          :class="(index===0 && flowplan.quantity > 0) ? 'border-top' : ''"
        >
          <!-- Item column - with or without alternates -->
          <td style="width: 100%; max-width: 0; overflow: hidden; text-overflow: ellipsis" v-if="!flowplan.alternates">
            <div class="d-flex align-items-center">
              <span
                v-if="flowplan.buffer?.description"
                data-bs-toggle="tooltip"
                :title="flowplan.buffer.description"
                class="text-truncate"
                style="min-width: 0; padding-right: 3px"
              >
                {{ flowplan.buffer?.item }}
              </span>
              <span
                v-else
                class="text-truncate"
                style="min-width: 0; padding-right: 3px"
                :title="flowplan.buffer?.item"
                data-bs-toggle="tooltip"
              >
                {{ flowplan.buffer?.item }}
              </span>
              <a
                :href="`${urlPrefix}/detail/input/item/${adminEscape(flowplan.buffer?.item)}/`"
                @click.stop
                class="flex-shrink-0"
              >
                <span class="fa fa-caret-right"></span>
              </a>
            </div>
          </td>

          <td style="width: 100%; max-width: 0; overflow: hidden; text-overflow: ellipsis" v-else>
            <div class="dropdown d-flex w-100">
              <button
                  class="btn btn-primary text-capitalize"
                  data-bs-toggle="dropdown"
                  type="button"
                  style="min-width: 150px"
              >
                {{ flowplan.buffer?.item }}
              </button>
              <ul class="dropdown-menu">
                <li>
                  <a
                      role="menuitem"
                      class="dropdown-item text-capitalize"
                      @click.prevent="selectAlternateItem(flowplan, flowplan.buffer?.item)"
                  >
                    {{ flowplan.buffer?.item }}
                  </a>
                </li>
                <li v-for="(alternate, altIndex) in flowplan.alternates" :key="altIndex">
                  <a
                      role="menuitem"
                      class="dropdown-item text-capitalize"
                      @click.prevent="selectAlternateItem(flowplan, alternate)"
                  >
                    {{ alternate }}
                  </a>
                </li>
              </ul>
            </div>
          </td>

          <!-- Location column -->
          <td class="w-auto text-center px-3" v-if="store.operationplan.type === 'DO'">{{ flowplan.buffer?.location }}</td>

          <!-- Quantity column -->
          <td class="w-auto text-center px-3">{{ numberFormat(flowplan.quantity) }}</td>

          <!-- Onhand column -->
          <td class="w-auto text-center px-3">{{ numberFormat(flowplan.onhand) }}</td>

          <!-- Date column -->
          <td class="w-auto text-center px-3" style="white-space: nowrap">{{ dateTimeFormat(flowplan.date) }}</td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
