<template>
  <div>
    <div class="select mr-1">
      <select
        ref="queueOptions"
        v-model="queueSelection"
        aria-label="Queue Selection"
        @change="changedSelection"
      >
        <option :value="-2">None</option>
        <option :value="-1">New Queue</option>
        <option v-for="(queue, i) in queues" v-bind:key="i" :value="queue.id">
          {{ queue.name }}
        </option>
      </select>
    </div>
    <div v-if="queueSelection === -1" class="is-flex is-flex-direction-row is-flex-grow-1 ml-1">
      <input
        v-model="queueName"
        aria-label="Queue Name"
        class="input mr-1"
        placeholder="Queue Name"
        type="text"
        @blur="createdQueue"
      >
    </div>
    <div v-else-if="queueSelection >= 0" class="is-flex-grow-1 ml-1">
      <Draggable :list="queueMembers" tag="div" @change="reorder">
        <div
          class="p-2 has-background-grey-dark edit-queue-list-item"
          v-for="element in queueMembers"
          :key="element.order"
        >
          <div>
            <div>{{ element.title }} ({{ element.asset }})</div>
            <div>{{ element.order }}</div>
          </div>
        </div>
      </Draggable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  computed,
  ref,
  watch,
} from 'vue';
import {
  Queue,
  RewardFund,
} from '@/api/types';
import {
  getQueueMembers,
  getQueues,
} from '@/api/composed';
import { VueDraggableNext as Draggable } from 'vue-draggable-next';

interface QueueMember {
  id?: number;
  title: string;
  asset: string;
  order: number;
}

// eslint-disable-next-line no-undef
const props = defineProps<{ newMember: RewardFund & { order: number; } | undefined }>();

// eslint-disable-next-line no-undef
const emits = defineEmits(['selected', 'created']);

const queueSelection = ref(undefined as number | undefined);
const queueName = ref(undefined as string | undefined);
const queueMembers = ref(undefined as QueueMember[] | undefined);
const serverQueues = ref(0);

const reorder = () => {
  if (queueMembers.value) {
    for (let i = 0; i < queueMembers.value.length; i += 1) {
      if (queueMembers.value[i]) {
        queueMembers.value[i].order = (i + 1);
      }
    }
  }
};

const queues = ref([] as Queue[]);
const fetchQueues = async () => {
  const resp = await getQueues();
  if (resp) {
    queues.value = resp.queues;
  }
};

await fetchQueues();

const changedSelection = () => {
  emits('selected', queueSelection.value);
};

const createdQueue = () => {
  emits('created', queueName.value);
};

const populateQueueMembers = async (id: number) => {
  const resp = await getQueueMembers(id) as { members: (RewardFund & { order: number; })[] };
  queueMembers.value = resp?.members.map((m) => ({
    id: m.id,
    title: m.title,
    asset: m.asset,
    order: m.order,
  }));

  if (props.newMember) {
    serverQueues.value = queueMembers.value.length;

    if (queueMembers.value && props.newMember.title && props.newMember.asset) {
      const newMember = {
        id: undefined,
        title: props.newMember.title,
        asset: props.newMember.asset,
        order: queueMembers.value.length + 1,
      };

      queueMembers.value.push(newMember);
    }
  }
};

watch(queueSelection, async (newValue) => {
  if (newValue !== undefined && newValue >= 0) {
    await populateQueueMembers(newValue);
  }
});

const addedMember = computed(() => props.newMember);

watch(addedMember, (newVal) => {
  if (newVal && newVal.title && newVal.asset) {
    const assembleNewMember = (order: number) => ({
      id: undefined,
      title: newVal.title,
      asset: newVal.asset,
      order,
    });
    const newMember = ref(undefined as QueueMember | undefined);
    if (queueMembers.value && serverQueues.value < queueMembers.value.length) {
      const newIndex = queueMembers.value.findIndex((m) => m.id === undefined);
      newMember.value = assembleNewMember(queueMembers.value[newIndex].order);
      queueMembers.value?.splice(newIndex, 1);

      if (queueMembers.value) {
        queueMembers.value.splice(newIndex, 0, newMember.value);
      } else {
        queueMembers.value = [newMember.value];
      }
    } else if (queueMembers.value && serverQueues.value === queueMembers.value.length) {
      newMember.value = assembleNewMember(queueMembers.value.length + 1);
      queueMembers.value.push(newMember.value);
    }
  }
}, { deep: true });

// TODO: send new order of queued items
</script>

<style lang="stylus" scoped>
input::placeholder, textarea::placeholder
  color #7d7d7d

.edit-queue-list
  border 1px #ccc solid
  border-radius 4px
  overflow hidden

.edit-queue-list-item
  cursor pointer

  &:not(:last-child)
    border-bottom 1px #a7a7a7 solid
</style>
