<template>
  <div>
    <DefaultHeaderPage title="Atividades" :show-filter-icon="false" />

    <div v-if="loading" class="flex flex-center q-pa-xl">
      <q-spinner color="primary" size="48px" />
    </div>

    <div
      v-else
      class="kanban-board q-px-md q-pb-md"
      style="
        display: flex;
        gap: 16px;
        overflow-x: auto;
        align-items: flex-start;
        min-height: calc(100vh - 120px);
      "
    >
      <div
        v-for="column in columns"
        :key="column.phase"
        style="
          min-width: 280px;
          max-width: 320px;
          flex: 1;
          display: flex;
          flex-direction: column;
          gap: 8px;
        "
      >
        <!-- Column header -->
        <div
          class="row items-center justify-between q-px-md q-py-sm"
          :style="{ backgroundColor: column.color, borderRadius: '8px' }"
        >
          <span class="text-weight-bold text-white" style="font-size: 14px">
            {{ column.label }}
          </span>
          <div class="row items-center gap-xs">
            <q-badge
              color="white"
              :text-color="column.badgeTextColor"
              :label="columnMap[column.phase].length"
              style="font-size: 11px"
            />
            <q-btn
              v-if="canAdd"
              flat
              round
              dense
              icon="mdi-plus"
              color="white"
              size="sm"
              @click="openDialog(null, column.phase)"
            />
          </div>
        </div>

        <!-- Draggable card list -->
        <draggable
          :list="columnMap[column.phase]"
          :data-phase="column.phase"
          :group="canEdit ? 'kanban' : { name: 'kanban', pull: false, put: false }"
          :disabled="!canEdit"
          item-key="id"
          :animation="180"
          ghost-class="drag-ghost"
          drag-class="drag-active"
          style="display: flex; flex-direction: column; gap: 8px; min-height: 48px; flex: 1"
          @end="onDragEnd"
        >
          <template #item="{ element }">
            <KanbanCard
              :card="element"
              :can-edit="canEdit"
              :can-delete="canDelete"
              @edit="canEdit && openDialog(element, column.phase)"
              @delete="removeCard($event, column.phase)"
            />
          </template>
        </draggable>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, defineAsyncComponent, onMounted } from "vue";
import { useQuasar } from "quasar";
import draggable from "vuedraggable";

import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import KanbanCard from "./components/KanbanCard.vue";
import { getKanbans, reorderKanbans } from "src/api/kanban";
import { permissionStore } from "src/stores/permission";

const AddEditKanbanDialog = defineAsyncComponent(
  () => import("./components/AddEditKanbanDialog.vue"),
);

const $q = useQuasar();
const permissions = permissionStore();
const canAdd = permissions.getAccess("franchisor_activities", "add");
const canEdit = permissions.getAccess("franchisor_activities", "edit");
const canDelete = permissions.getAccess("franchisor_activities", "delete");
const loading = ref(false);

const columns = [
  { phase: "a_fazer",            label: "A Fazer",            color: "#757575", badgeTextColor: "grey-9"   },
  { phase: "em_progresso",       label: "Em Progresso",       color: "#1976D2", badgeTextColor: "blue-9"   },
  { phase: "em_revisao",         label: "Em Revisão",         color: "#F57C00", badgeTextColor: "orange-9" },
  { phase: "concluido",          label: "Concluído",          color: "#388E3C", badgeTextColor: "green-9"  },
  { phase: "demandas_especiais", label: "Demandas Especiais", color: "#F9A825", badgeTextColor: "yellow-9" },
];

// Each phase has its own reactive array — required for vuedraggable cross-list DnD
const columnMap = reactive({
  a_fazer: [],
  em_progresso: [],
  em_revisao: [],
  concluido: [],
  demandas_especiais: [],
});

const loadCards = async () => {
  loading.value = true;
  try {
    const data = await getKanbans();

    // Reset all columns before filling
    Object.keys(columnMap).forEach((k) => (columnMap[k] = []));

    data.forEach((card) => {
      if (columnMap[card.phase]) {
        columnMap[card.phase].push(card);
      }
    });
  } finally {
    loading.value = false;
  }
};

/**
 * Called once when drag ends.
 * By this point vuedraggable has already moved the item between the two arrays.
 * We read source/destination phases from the DOM data-phase attribute and persist.
 */
const onDragEnd = async (evt) => {
  const sourcePhase = evt.from.dataset.phase;
  const targetPhase = evt.to.dataset.phase;

  // Collect phases to update (may be the same if reordering in-column)
  const phasesToUpdate = new Set([sourcePhase, targetPhase].filter(Boolean));

  const items = [];
  phasesToUpdate.forEach((phase) => {
    columnMap[phase].forEach((card, idx) => {
      // Sync the card's phase in memory too
      card.phase = phase;
      items.push({ id: card.id, phase, order: idx });
    });
  });

  try {
    await reorderKanbans(items);
  } catch {
    // On failure restore from server
    await loadCards();
  }
};

const removeCard = (cardId, phase) => {
  const idx = columnMap[phase].findIndex((c) => c.id === cardId);
  if (idx !== -1) columnMap[phase].splice(idx, 1);
};

const openDialog = (card = null, phase = "a_fazer") => {
  $q.dialog({
    component: AddEditKanbanDialog,
    componentProps: { card, initialPhase: phase },
  }).onOk(() => {
    loadCards();
  });
};

onMounted(loadCards);
</script>

<style scoped>
.kanban-board {
  padding-top: 12px;
}

:deep(.drag-ghost) {
  opacity: 0.4;
  border: 2px dashed #aaa;
  border-radius: 10px;
}

:deep(.drag-active) {
  opacity: 0.95;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
  transform: rotate(1.5deg);
}
</style>
