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

    <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"
    >
      <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;
        "
      >
        <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"
              style="font-size: 11px"
              :label="columnMap[column.phase].length"
              :text-color="column.badgeTextColor"
            />

            <q-btn
              v-if="canAdd"
              color="white"
              dense
              flat
              icon="mdi-plus"
              round
              size="sm"
              @click="openDialog(null, column.phase)"
            />
          </div>
        </div>

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

<script setup>
import {
  computed,
  defineAsyncComponent,
  onMounted,
  reactive,
  ref,
  watch,
} from "vue";

import { getKanbans, reorderKanbans } from "src/api/kanban";
import { permissionStore } from "src/stores/permission";
import { useQuasar } from "quasar";
import { userStore } from "src/stores/user";

import draggable from "vuedraggable";

import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import KanbanCard from "./components/KanbanCard.vue";

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

const $q = useQuasar();

const permissions = permissionStore();
const { selectedUnit } = userStore();

const loading = ref(false);

const columnMap = reactive({
  a_fazer: [],
  concluido: [],
  demandas_especiais: [],
  em_progresso: [],
  em_revisao: [],
});

const canAdd = computed(() =>
  permissions.getAccess("franchisee_activities", "add"),
);

const canDelete = computed(() =>
  permissions.getAccess("franchisee_activities", "delete"),
);

const canEdit = computed(() =>
  permissions.getAccess("franchisee_activities", "edit"),
);

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

const loadCards = async () => {
  loading.value = true;

  try {
    const data = await getKanbans();

    Object.keys(columnMap).forEach((phase) => {
      columnMap[phase] = [];
    });

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

const onDragEnd = async (event) => {
  const sourcePhase = event.from.dataset.phase;
  const targetPhase = event.to.dataset.phase;

  const phasesToUpdate = new Set(
    [sourcePhase, targetPhase].filter(Boolean),
  );

  const items = [];

  phasesToUpdate.forEach((phase) => {
    columnMap[phase].forEach((card, index) => {
      card.phase = phase;

      items.push({
        id: card.id,
        order: index,
        phase,
      });
    });
  });

  try {
    await reorderKanbans(items);
  } catch {
    await loadCards();
  }
};

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

const removeCard = (cardId, phase) => {
  const index = columnMap[phase].findIndex(
    (card) => card.id === cardId,
  );

  if (index !== -1) {
    columnMap[phase].splice(index, 1);
  }
};

watch(
  () => selectedUnit?.id,
  (newId, oldId) => {
    if (newId === oldId) return;

    loadCards();
  },
);

onMounted(loadCards);
</script>

<style scoped>
.kanban-board {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  grid-auto-rows: max-content;
  align-items: start;
  align-content: start;
  gap: 16px;
  width: 100%;
  max-width: 100%;
  min-width: 0;
  min-height: calc(100vh - 120px);
  box-sizing: border-box;
  overflow-x: hidden;
  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 rgb(0 0 0 / 18%);
  transform: rotate(1.5deg);
}
</style>