<template>
  <div
    :style="{ maxHeight, overflowY: 'auto' }"
    @scroll="handleScroll"
  >
    <table
      v-if="inContext"
      class="table is-bordered is-hoverable is-fullwidth"
    >
      <tbody>
        <tr
          v-for="(v, i) in rows"
          :key="i"
          @click="doClick(v, i)"
          class="fs-14 is-clickable"
        >
          <td>
            <span>{{ $stripHtml(v[name] || v.fullname || v.code || "n/a", 75) }}</span>
            <span
              v-if="tick && checked[i]"
              class="icon right-3 has-background-inherit"
            >
              <Icon
                name="material-symbols:check-rounded"
                :size="17"
                class="has-text-primary"
              />
            </span>
          </td>
        </tr>
      </tbody>
    </table>
    <div
      v-else
      v-for="(v, i) in rows"
      :key="i"
    >
      <button
        class="button is-white rounded-none fs-14 font-normal w-full is-justify-content-space-between"
        type="button"
        @click="doClick(v, i)"
      >
        <span>{{ $stripHtml(v[name] || v.fullname || v.code || "n/a", 75) }}</span>
        <span
          v-if="tick && checked[i]"
          class="icon right-3 has-background-inherit"
        >
          <Icon
            name="material-symbols:check-rounded"
            :size="17"
            class="has-text-primary"
          />
        </span>
      </button>
    </div>
  </div>
</template>
<script setup>
const props = defineProps({
  data: Array,
  name: String,
  maxHeight: String,
  perpage: Number,
  sort: String,
  selects: String,
  keyval: String,
  tick: {
    type: Boolean,
    default: true,
  },
  inContext: Boolean,
  clearTrigger: Number,
});

const emit = defineEmits(["selected"]);
const { $copy, $multiSort, $remove } = useNuxtApp();
const currentPage = ref(1);
const total = ref(props.data.length);
const rows = ref(props.data.slice(0, props.perpage));
const selected = ref([]);
const checked = ref({});
const array = ref([]);

getdata();

watch(
  () => props.data,
  () => getdata(),
  { deep: true },
);

watch(
  () => props.selects,
  (newVal) => {
    console.log("props.selects changed", newVal);
    getSelect();
  },
  { deep: true },
);

watch(
  () => props.clearTrigger,
  () => {
    checked.value = {};
  },
);

function getdata() {
  currentPage.value = 1;
  array.value = $copy(props.data);
  if (props.sort) {
    const f = {};

    if (props.sort.startsWith("-")) {
      f[props.sort.slice(1)] = "desc";
    } else {
      f[props.sort] = "asc";
    }

    $multiSort(array.value, f);
  }
  rows.value = array.value.slice(0, props.perpage);
  getSelect();
}

function getSelect() {
  if (!props.selects) return;
  selected.value = [];
  checked.value = {};
  props.selects.map((v) => {
    const idx = rows.value.findIndex((x) => x[props.keyval ? props.keyval : props.name] === v);
    if (idx >= 0) {
      selected.value.push(rows.value[idx]);
      checked.value[idx] = true;
    }
  });
}

function doClick(v, i, type) {
  checked.value = { [i]: true };
  const idx = selected.value.findIndex((x) => x.id === v.id);
  idx >= 0 ? $remove(selected.value) : selected.value.push(v);
  emit("selected", v, type);
}

function handleScroll(e) {
  const bottom = e.target.scrollHeight - e.target.scrollTop - 5 < e.target.clientHeight;
  if (bottom) {
    if (total.value ? total.value > rows.value.length : true) {
      currentPage.value += 1;
      let arr = array.value.filter(
        (_, index) => index >= (currentPage.value - 1) * props.perpage && index < currentPage.value * props.perpage,
      );
      rows.value = rows.value.concat(arr);
    }
  }
}
</script>
<style scoped>
.button.is-ghost {
  color: var(--bulma-button-text-color);
}
.button.is-ghost:hover,
.button.is-ghost.is-hovered {
  color: var(--bulma-button-ghost-hover-color);
}
</style>
