<script setup lang="ts">
import { VueDraggableNext } from 'vue-draggable-next'
import { type Issue, useIssuesStore } from '@/stores/issues.ts'
import { ref } from 'vue'
import type { Status } from '@/stores/statuses.ts'
import IssueListItem from '@/components/IssueListItem.vue'
import IssueCreateForm from '@/components/IssueCreateForm.vue'

const props = defineProps<{ issues: Issue[]; status: Status }>()

const issuesStore = useIssuesStore()

const selectedId = ref<number>()

const height = 400

async function onChange(val: {
  added: { element: Issue; newIndex: number }
  moved: { element: Issue; oldIndex: number; newIndex: number }
  removed: { element: Issue; oldIndex: number }
}) {
  selectedId.value = val.moved?.element.id

  const body = {
    status_id: props.status.id,
    positions: props.issues.map((i) => i.id),
  }

  if (val.moved || val.added) {
    await issuesStore.updatePositions(body)
  }
}

function onChoose() {
  selectedId.value = undefined
}
</script>

<template>
  <v-sheet rounded>
    <v-toolbar density="compact">
      <v-toolbar-title>
        <div class="d-flex align-center ga-2">
          <div class="text-uppercase text-body-2">{{ props.status.name }}</div>
          <v-chip size="small" variant="tonal" :text="props.issues.length" class="mr-2" />
        </div>
      </v-toolbar-title>
      <template #append>
        <v-menu>
          <template v-slot:activator="{ props }">
            <v-chip label variant="text" v-bind="props">
              <v-icon icon="mdi-dots-horizontal"></v-icon>
            </v-chip>
          </template>

          <v-list density="compact" class="mt-1">
            <v-list-item v-for="(item, i) in 3" :key="i" :value="i">
              <v-list-item-title>{{ item }} - menu</v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
      </template>
    </v-toolbar>

    <v-list lines="two" rounded :height="height" slim class="mx-2">
      <VueDraggableNext
        :list="props.issues"
        :animation="0"
        handle=".handle"
        group="issues"
        ghostClass="sortable-ghost"
        dragClass="sortable-drag"
        @change="onChange"
        @choose="onChoose"
      >
        <issue-list-item v-for="issue in props.issues" :key="issue.id" :issue></issue-list-item>
      </VueDraggableNext>

      <issue-create-form :status="props.status"></issue-create-form>
    </v-list>
  </v-sheet>
</template>

<style scoped lang="scss">
.sortable-ghost {
  opacity: 0.33;
  transition: opacity 0.3s;
}
.sortable-drag {
  background-color: rgb(var(--v-theme-background));
}
.animation {
  animation: wave 0.5s linear;
}
@keyframes wave {
  50% {
    background-color: rgba(var(--v-theme-primary), 0.2);
  }
}
</style>
