<template>
  <div>
    <DefaultHeaderPage title="Suporte" :show-filter-icon="false" />
    <DefaultTable
      ref="tableRef"
      :columns="columns"
      :api-call="getSupportTickets"
      :add-item="canAdd"
      title="Tickets"
      :female="false"
      description="tickets"
      @on-add-item="openAddEditTicketDialog()"
    >
      <template #body-cell-severity="{ row }">
        <q-td align="left">
          <q-badge
            :color="severityColor(row.severity)"
            :label="severityLabel(row.severity)"
            style="padding: 6px 10px"
          />
        </q-td>
      </template>

      <template #body-cell-origin="{ row }">
        <q-td align="left">{{ originLabel(row) }}</q-td>
      </template>

      <template #body-cell-target="{ row }">
        <q-td align="left">{{ targetLabel(row) }}</q-td>
      </template>

      <template #body-cell-status="{ row }">
        <q-td align="left">
          <q-badge
            :color="statusColor(row.status)"
            :label="statusLabel(row.status)"
            style="padding: 6px 10px"
          />
        </q-td>
      </template>

      <template #body-cell-actions="{ row }">
        <q-td
          style="
            display: flex;
            gap: 4px;
            align-items: center;
            justify-content: center;
          "
        >
          <q-btn
            v-if="canEdit"
            outline
            icon="mdi-pencil-outline"
            style="width: 36px"
            @click.prevent.stop="handleEdit(row)"
          />

          <q-btn
            v-if="canEdit && row.status === 'in_progress'"
            outline
            icon="mdi-check-circle-outline"
            style="width: 36px"
            @click.prevent.stop="handleClose(row)"
          />

          <q-btn
            v-if="canDelete && row.status === 'in_progress'"
            outline
            icon="mdi-trash-can-outline"
            style="width: 36px"
            @click.prevent.stop="handleDelete(row)"
          />
        </q-td>
      </template>
    </DefaultTable>
  </div>
</template>

<script setup>
import { defineAsyncComponent, useTemplateRef } from "vue";
import { useQuasar } from "quasar";

import DefaultTable from "src/components/defaults/DefaultTable.vue";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import { getSupportTickets, deleteSupportTicket } from "src/api/support_ticket";
import { permissionStore } from "src/stores/permission";

const AddEditTicketDialog = defineAsyncComponent(
  () => import("src/pages/support/components/AddEditTicketDialog.vue"),
);

const CloseTicketDialog = defineAsyncComponent(
  () => import("src/pages/support/components/CloseTicketDialog.vue"),
);

const $q = useQuasar();
const permissions = permissionStore();
const canAdd = permissions.getAccess("franchisor_support", "add");
const canEdit = permissions.getAccess("franchisor_support", "edit");
const canDelete = permissions.getAccess("franchisor_support", "delete");
const tableRef = useTemplateRef("tableRef");

const openAddEditTicketDialog = (ticket = null) => {
  $q.dialog({
    component: AddEditTicketDialog,
    componentProps: { ticket },
  }).onOk(() => {
    tableRef.value?.refresh();
  });
};

const columns = [
  {
    name: "id",
    label: "Ticket",
    field: "id",
    align: "left",
    style: "width: 5%",
    format: (val) => `#${String(val).padStart(6, "0")}`,
  },
  {
    name: "severity",
    label: "Prioridade",
    field: "severity",
    align: "left",
    style: "width: 8%",
  },
  {
    name: "created_at",
    label: "Data",
    field: "created_at",
    align: "left",
    style: "width: 10%",
  },
  {
    name: "origin",
    label: "Origem",
    field: "origin",
    align: "left",
    style: "width: 12%",
  },
  {
    name: "target",
    label: "Destino",
    field: "target_unit_name",
    align: "left",
    style: "width: 12%",
  },
  {
    name: "sector",
    label: "Setor",
    field: "sector",
    align: "left",
    style: "width: 12%",
  },
  {
    name: "title",
    label: "Título",
    field: "title",
    align: "left",
    style: "width: 21%",
  },
  {
    name: "status",
    label: "Status",
    field: "status",
    align: "left",
    style: "width: 10%",
  },
  {
    name: "actions",
    label: "Ações",
    field: "actions",
    align: "center",
    style: "width: 10%",
  },
];

const originLabel = (row) => {
  if (row.origin === "matriz") return "Matriz";
  return row.applicant_unit_name ?? "Unidade";
};

const targetLabel = (row) => {
  if (row.scope === "internal") return "Interno";
  return row.target_unit_name ?? "—";
};

const severityLabel = (severity) => {
  const map = { alta: "Alta", normal: "Normal", baixa: "Baixa" };
  return map[severity] ?? severity;
};

const severityColor = (severity) => {
  const map = { alta: "negative", normal: "warning", baixa: "positive" };
  return map[severity] ?? "grey";
};

const statusLabel = (status) => {
  const map = {
    in_progress: "Em andamento",
    resolved: "Resolvido",
    unresolved: "Não resolvido",
  };
  return map[status] ?? status;
};

const statusColor = (status) => {
  const map = {
    in_progress: "warning",
    resolved: "positive",
    unresolved: "negative",
  };
  return map[status] ?? "grey";
};

const handleEdit = (row) => {
  openAddEditTicketDialog(row);
};

const handleClose = (row) => {
  $q.dialog({
    component: CloseTicketDialog,
    componentProps: { ticket: row },
  }).onOk(() => {
    tableRef.value?.refresh();
  });
};

const handleDelete = (row) => {
  $q.dialog({
    title: "Confirmar exclusão",
    message: "Tem certeza que deseja excluir este ticket?",
    ok: { color: "negative", label: "Excluir" },
    cancel: { color: "primary", outline: true, label: "Cancelar" },
  }).onOk(async () => {
    await deleteSupportTicket(row.id);
    tableRef.value?.refresh();
  });
};
</script>
