<template>
  <q-drawer
    v-model="columnDrawerOpen"
    overlay
    no-swipe-open
    side="right"
  >
    <div
      :class="'column full-height ' + headerColor"
      test-id="columnsDrawer"
      :style="'background-color:' + headerColor"
    >
      <div class="columnsDrawer__closeButton">
        <div class="text-left">
          {{ $t("configureColumns") }}
        </div>
        <span
          class="gt-sm"
          test-id="closeColumnDrawer"
          @click="columnDrawerOpen = !columnDrawerOpen"
        >
          <ExitIcon />
        </span>
      </div>
      <div class="q-pt-xl q-px-lg q-pb-md col items-start text-k-accent overflow-auto">
        <ul
          ref="columnDrawer"
          style="padding: 0; width: 90%"
          test-id="columnDrawer"
        >
          <li
            v-for="column in columns"
            :key="column.label"
            class="row no-wrap items-center justify-between"
          >
            <div class="row no-wrap items-center">
              <q-checkbox
                v-if="visibleColumns.length > 0"
                v-model:model-value="visibleColumns[visibleColumns.findIndex((col) => col.name === column.name)].isVisible"
                square
                :test-id="column.name + 'Checkbox'"
              />
              <span style="text-align: start">{{ column.label }}</span>
            </div>
            <q-icon
              :test-id="column.name + 'Drag'"
              class="columnDrawer__handle float-right"
              name="drag_handle"
              size="1.5rem"
            />
          </li>
        </ul>
      </div>
    </div>
  </q-drawer>
</template>
<script setup>
import ExitIcon from '@assets/icons/ExitKettal.svg'
import { onMounted, ref } from 'vue'
import Sortable from 'sortablejs'

const visibleColumns = defineModel('visibleColumns', { type: Array, required: true, default: [] })
const columnDrawerOpen = defineModel('columnDrawerOpen', { type: Boolean, required: true, default: false })

defineProps({
  /** Color of the header */
  headerColor: {
    type: String,
    default: '#e3ddd6'
  },
  /** Data of all columns */
  columns: { type: Array, required: true }
})
const columnDrawer = ref(null)

onMounted(() => {
  Sortable.create(columnDrawer.value, {
    animation: 150,
    ghostClass: 'blue-background-class',
    handle: '.columnDrawer__handle',
    onEnd: (evt) => {
      const columnToBeMoved = visibleColumns.value.splice(evt.oldIndex, 1)
      visibleColumns.value.splice(evt.newIndex, 0, columnToBeMoved[0])
    }
  })
})

</script>
