<template>
  <div>
    <DefaultHeaderPage title="Contratos" />

    <div class="q-px-sm">
      <div class="stat-cards-row q-mb-md">
        <DashboardStatCard
          title="Contratos Ativos"
          icon="mdi-file-check-outline"
          :value="String(metrics.active)"
        />
        <DashboardStatCard
          title="Contratos Trancados"
          icon="mdi-snowflake"
          :value="String(metrics.frozen)"
        />
        <DashboardStatCard
          title="Contratos Cancelados"
          icon="mdi-file-remove-outline"
          :value="String(metrics.cancelled)"
        />
        <DashboardStatCard
          title="Contratos Inadimplentes"
          icon="mdi-alert-circle-outline"
          value="0"
        />
      </div>

      <DefaultTable
        v-model:rows="rows"
        title="Contratos"
        :columns
        descricao="contratos"
        :feminino="false"
        no-api-call
        :loading="isLoading"
      >
        <template #body-cell-contato="{ row }">
          <q-td>
            <div>{{ row.student_phone }}</div>
            <div class="text-grey-6 text-caption">
              {{ row.student_city }}<template v-if="row.student_city && row.student_state_code">, </template>{{ row.student_state_code }}
            </div>
          </q-td>
        </template>

        <template #body-cell-status="{ row }">
          <q-td align="center">
            <q-badge
              :color="statusColor(row.status)"
              :label="statusLabel(row.status)"
            />
          </q-td>
        </template>

        <template #body-cell-actions="{ row }">
          <q-td align="center">
            <q-item-section class="no-wrap" style="flex-direction: row; gap: 4px">
            <q-btn
              outline
              icon="mdi-eye-outline"
              style="width: 36px"
              @click.prevent.stop="handleView(row)"
            />
            <q-btn
              v-if="canEdit"
              outline
              icon="mdi-dots-vertical"
              style="width: 36px"
              @click.prevent.stop
            >
              <q-menu>
                <q-list style="min-width: 170px">
                  <template v-if="row.status === 'frozen' || row.status === 'cancelled'">
                    <q-item
                      v-close-popup
                      clickable
                      @click="handleReactivate(row)"
                    >
                      <q-item-section>Reativar Contrato</q-item-section>
                    </q-item>
                  </template>
                  <template v-else>
                    <q-item
                      v-close-popup
                      clickable
                      @click="handleFreeze(row)"
                    >
                      <q-item-section>Trancar Contrato</q-item-section>
                    </q-item>
                    <q-item
                      v-close-popup
                      clickable
                      @click="handleCancel(row)"
                    >
                      <q-item-section>Cancelar Contrato</q-item-section>
                    </q-item>
                  </template>
                </q-list>
              </q-menu>
            </q-btn>
            </q-item-section>
          </q-td>
        </template>
      </DefaultTable>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useQuasar } from "quasar";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import DashboardStatCard from "src/components/charts/DashboardStatCard.vue";
import { userStore } from "src/stores/user";
import { permissionStore } from "src/stores/permission";
import ContractActionConfirmDialog from "src/pages/students/components/ContractActionConfirmDialog.vue";
import FreezeContractDialog from "src/pages/students/components/FreezeContractDialog.vue";
import ViewContractDialog from "src/pages/students/components/ViewContractDialog.vue";
import {
  getAllContracts,
  cancelContract,
  reactivateContract,
} from "src/api/studentContract";

const $q = useQuasar();
const store = userStore();
const permissions = permissionStore();
const canEdit = computed(() =>
  permissions.getAccess("franchisee_contracts", "edit"),
);
const rows = ref([]);
const isLoading = ref(false);

const metrics = computed(() => ({
  active: rows.value.filter((r) => r.status === "active").length,
  frozen: rows.value.filter((r) => r.status === "frozen").length,
  cancelled: rows.value.filter((r) => r.status === "cancelled").length,
}));

const columns = ref([
  { name: "name", label: "Nome", field: "student_name", align: "left" },
  { name: "contato", label: "Contato/Endereço", field: null, align: "left" },
  { name: "package_name", label: "Pacote", field: "package_name", align: "left" },
  { name: "status", label: "Status Contrato", field: "status", align: "center" },
  { name: "actions", label: "Ações", field: null, align: "center" },
]);

async function loadContracts() {
  isLoading.value = true;
  try {
    rows.value = await getAllContracts();
  } finally {
    isLoading.value = false;
  }
}

function handleView(contract) {
  $q.dialog({
    component: ViewContractDialog,
    componentProps: { id: contract.id },
  });
}

function confirmAction(title, message, apiFn, contract) {
  $q.dialog({
    component: ContractActionConfirmDialog,
    componentProps: { title, message },
  }).onOk(async () => {
    try {
      const updated = await apiFn(contract.id);
      const idx = rows.value.findIndex((r) => r.id === contract.id);
      if (idx !== -1) rows.value[idx] = { ...rows.value[idx], status: updated.status };
    } catch (e) {
      console.error(e);
      $q.notify({ type: "negative", message: "Erro ao atualizar status do contrato." });
    }
  });
}

function handleFreeze(contract) {
  $q.dialog({
    component: FreezeContractDialog,
    componentProps: { contract },
  }).onOk((updated) => {
    const idx = rows.value.findIndex((r) => r.id === contract.id);
    if (idx !== -1) rows.value[idx] = { ...rows.value[idx], status: updated.status };
  });
}

function handleCancel(contract) {
  confirmAction(
    "Cancelar Contrato",
    "Você tem certeza que deseja CANCELAR este contrato? Isso irá gerar multas e cancelamento da cobrança recorrente.",
    cancelContract,
    contract,
  );
}

function handleReactivate(contract) {
  confirmAction(
    "Reativar Contrato",
    "Você tem certeza que deseja REATIVAR este contrato?",
    reactivateContract,
    contract,
  );
}

function statusColor(status) {
  if (status === "active") return "positive";
  if (status === "frozen") return "info";
  if (status === "cancelled") return "negative";
  return "warning";
}

function statusLabel(status) {
  if (status === "active") return "Ativo";
  if (status === "frozen") return "Trancado";
  if (status === "cancelled") return "Cancelado";
  return "Inativo";
}

watch(
  () => store.selectedUnit?.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) loadContracts();
  },
);

onMounted(loadContracts);
</script>

<style scoped lang="scss">
.stat-cards-row {
  display: flex;
  flex-wrap: nowrap;
  gap: 12px;
}

.stat-cards-row > * {
  flex: 1 1 0;
  min-width: 0;
}

@media (max-width: 768px) {
  .stat-cards-row {
    flex-wrap: wrap;
  }

  .stat-cards-row > * {
    flex: 1 1 calc(50% - 8px);
  }
}
</style>
