<template>
  <section class="relative pt-16 pb-32 justify-center">
    <div class="mx-auto px-1 lg:px-4">
      <Container
        class="h-full flex overflow-x-auto gap-8 p-8"
        group-name="cols"
        tag="div"
        orientation="horizontal"
        > <!--  @drop="onColumnDrop($event)"  -->
        <div class="bg-gray-200 dark:bg-gray-700 rounded-lg h-full w-96 flex-shrink-0 shadow-xl"
          v-for="(column, columnIndex) in scene" :key="column.id">
          <div class="h-full flex flex-col">
            <!-- header-->
            <div class="cursor-move rounded-t-lg p-4 space-x-4 bg-rose-medium text-white flex space-x-2">
              <PaperAirplaneIcon class="h-6 w-6"></PaperAirplaneIcon>
              <span class="text-lg uppercase">{{ column.name }}</span>
            </div>
            <!-- column -->
            <Container
              class="flex-grow overflow-y-auto overflow-x-hidden"
              
              group-name="col-items"
              :shouldAcceptDrop="(e, payload) =>  (e.groupName === 'col-items' && !payload.loading)"
              :get-child-payload="getCardPayload(column.id)"
              :drop-placeholder="{ className: 
                `bg-primary bg-opacity-20  
                border-dotted border-2 
                border-primary rounded-lg mx-4 my-2`, 
              animationDuration: '200', 
              showOnTop: true }"
              drag-class="bg-primary dark:bg-primary 
                border-2 border-primary-hover text-white 
                transition duration-100 ease-in z-50
                transform rotate-6 scale-110"
              drop-class="transition duration-100 
                ease-in z-50 transform 
                -rotate-2 scale-90"
              @drop="(e) => onCardDrop(column.id, e)">

                <!-- Items -->
                <!-- <TransitionGroup tag="div" name="tasks" class="flex flex-col gap-3"> -->
                <ManageItem v-for="(item, taskIndex) in column.tasks" :key="item.id" :item="item" :columnIndex="columnIndex" :taskIndex="taskIndex"></ManageItem>
                <!-- </TransitionGroup> -->
            </Container>
          </div>
        </div>
      </Container>
      
      <bgOverlay data-no-dragscroll />
      <div class="absolute top-16 z-10 max-w-max w-11/12">
        <TaskView v-if="systemStore.taskView" />
        <TaskForm v-if="systemStore.taskForm.visible" />
        <Delete v-if="systemStore.delete.visible" />
        <BoardForm v-if="systemStore.boardForm.visible" />
        <AppointmentTaskForm v-if="systemStore.appointmentTaskForm.visible" />
        <DiagnosisTaskForm v-if="systemStore.diagnosisTaskForm.visible" />
        <PrescriptionTaskForm v-if="systemStore.prescriptionTaskForm.visible" />
        <CompletionTaskForm v-if="systemStore.completionTaskForm.visible" />
        <HistoryView v-if="systemStore.historyView" />
      </div>
    </div>
  </section>
</template>

<script>
import { Container, Draggable } from 'vue3-smooth-dnd'
import { PaperAirplaneIcon, CodeIcon } from '@heroicons/vue/24/outline'
import { applyDrag, generateItems, generateWords } from '@/utils/helpers'

import { useBoardsStore } from '@/store/boards.js';
import { useSystemStore } from '@/store/system.js';
import Board from '@/components/board/Board.vue'
import bgOverlay from '@/components/utils/bgOverlay.vue';
import TaskView from '@/components/manager/TaskView.vue'
import TaskForm from '@/components/manager/TaskForm.vue';

import Delete from '@/components/manager/Delete.vue';
import BoardForm from '@/components/manager/BoardForm.vue';

import HistoryView from '@/views/admin/bundle/HistoryView.vue'
import AppointmentTaskForm from '@/views/admin/bundle/AppointmentTaskForm.vue';
import DiagnosisTaskForm from '@/views/admin/bundle/DiagnosisTaskForm.vue';
import PrescriptionTaskForm from '@/views/admin/bundle/PrescriptionTaskForm.vue';
import CompletionTaskForm from '@/views/admin/bundle/CompletionTaskForm.vue';

import ManageItem from '@/views/admin/bundle/ManageItem.vue'

// mock
const scene = []
export default {
  components: { 
    Container, Draggable, ManageItem, PaperAirplaneIcon, CodeIcon,
    Board, bgOverlay, TaskView, TaskForm, Delete, BoardForm, HistoryView, AppointmentTaskForm, DiagnosisTaskForm, PrescriptionTaskForm, CompletionTaskForm
  },
  data () {
    return {
      scene,
      boardsStore: useBoardsStore(),
      systemStore: useSystemStore(),
    }
  },
  // watch: {
  //   // watching top-level property
  //   scene(val, oldVal) {
  //     // console.log(val);
  //     // console.log(`new: ${val}, old: ${oldVal}`)
  //   },
  // },
  async mounted(){
    await this.boardsStore.todayLoad();

    this.scene = this.boardsStore.getCurrentBoard;
    // console.log(this.boardsStore.getCurrentBoard);
    
    // console.log(this.scene);

    
    this.$nextTick(function () {
      this.$refs.target?.scrollIntoView();
    });

  },
  unmounted(){
    this.systemStore.hideOverlay();
  },
  methods: {
    getColumnHeightPx(){
      let kanban = document.getElementById('kanbanContainer');
      return kanban ? kanban.offsetHeight - 122 : 0;
    },
    // onColumnDrop (dropResult) {
    //   console.log(dropResult);
    //   const scene = Object.assign({}, this.scene)
    //   scene.children = applyDrag(scene.children, dropResult)
    //   this.scene = scene
    // },
    onCardDrop (columnId, dropResult) {
      // check if element where ADDED or REMOVED in current collumn
      if (dropResult.removedIndex !== null || dropResult.addedIndex !== null) {
        
        const scene = Object.assign([], this.scene)
        const column = scene.filter(p => p.id === columnId)[0]
        const itemIndex = scene.indexOf(column)
        const newColumn = Object.assign({}, column)
        
        // check if element was ADDED in current column
        if((dropResult.removedIndex == null && dropResult.addedIndex >= 0)){
          // your action / api call
          // dropResult.payload.loading = true
          // simulate api call
          // setTimeout(function(){ dropResult.payload.loading = false }, (Math.random() * 5000) + 1000); 
          this.boardsStore.changeTaskColumn(itemIndex, dropResult.addedIndex, dropResult.payload);
        } 
        //  same column move
        else if(dropResult.removedIndex >= 0 && dropResult.addedIndex !== null) {
          //  Appointment 는 캐시를 통해 위치를 변경시킬 필요가 없다. 어차피 아래에서 정렬함.
          // this.boardsStore.changeTaskRow(itemIndex, dropResult.removedIndex, dropResult.addedIndex);
        }
        
        newColumn.tasks = applyDrag(newColumn.tasks, dropResult)
        scene.splice(itemIndex, 1, newColumn)
        
        //  sorted by startdt 
        // scene[Number(columnId.slice(-1))].tasks.sort(
        //   (objA, objB) => new Date(objA.startdt).getTime() - new Date(objB.startdt).getTime(),
        // );

        this.scene = scene
      }
    },
    getCardPayload (columnId) {
      // console.log(columnId);
      return index => {
        return this.scene.filter(p => p.id === columnId)[0].tasks[index]
      }
    },
    
  }
}
</script>
<style>
/** NB: dont remove, 
* When using orientation="horizontal" it auto sets "display: table"
* In this case we need flex and not display table  
*/
.smooth-dnd-container.horizontal{
  display: flex !important;
}

/* .tasks-enter-from {
  opacity: 0;
  transform: scale(0.75);
}

.tasks-enter-to {
  opacity: 1;
  transform: scale(1);
}

.tasks-enter-active {
  transition: all 0.5s ease;

} */
</style>