<template>
  <div>
    <DefaultHeaderPage />

    <div class="q-pa-sm">
      <div v-if="statsLoading" class="flex flex-center q-pa-xl">
        <q-spinner color="violet-normal" size="50px" />
      </div>

      <template v-else>
        <div class="row q-col-gutter-md q-mb-md">
          <div
            v-for="card in statCards"
            :key="card.key"
            class="col-12 col-sm-6 col-md-4 col-lg"
          >
            <q-card
              flat
              class="stat-card cursor-pointer bg-white"
              :class="{ 'stat-card--active': activeCard === card.key }"
              @click="onCardClick(card)"
            >
              <q-card-section class="q-pa-md">
                <q-icon :name="card.icon" size="28px" color="violet-normal" />
                <div class="text-h5 text-weight-bold q-mt-xs text-dark">
                  {{ stats[card.key] ?? '—' }}
                </div>
                <div class="text-caption text-grey-7 ellipsis">
                  {{ $t(card.labelKey) }}
                </div>
              </q-card-section>
            </q-card>
          </div>
        </div>

        <q-card v-if="activeCard" flat class="bg-white" style="border-radius: 12px">
          <DefaultTableServerSide
            :key="activeCard"
            :columns="tableColumns"
            :api-call="activeApiCall"
            :add-item="false"
            sem-table-top
            :show-search-field="activeCard !== 'ultimos_acessos'"
          >
            <template #body-cell-status="{ row }">
              <q-td>
                <q-badge
                  :color="getStatusColor(row.status)"
                  :label="$t(getStatusI18nKey(row.status))"
                  class="text-capitalize"
                  outline
                />
              </q-td>
            </template>

            <template #body-cell-user_type="{ row }">
              <q-td class="text-center">
                <q-badge
                  outline
                  :color="row.user_type === 'associado' ? 'violet-normal' : 'teal'"
                  :label="row.user_type === 'associado' ? $t('auth.type.associado') : $t('auth.type.parceiro')"
                />
              </q-td>
            </template>

            <template #body-cell-accessed_at="{ row }">
              <q-td>
                {{ formatDateTime(row.accessed_at) }}
              </q-td>
            </template>
          </DefaultTableServerSide>
        </q-card>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultTableServerSide from "src/components/defaults/DefaultTableServerSide.vue";
import { getDashboardStats } from "src/api/dashboard";
import { getUsersPaginated } from "src/api/user";
import { getPartnerAgreementsPaginated, getExpiringPartnerAgreementsPaginated } from "src/api/partnerAgreement";
import { getAccessLogsPaginated } from "src/api/userAccessLog";
import { formatDateYMDtoDMY, getStatusColor, getStatusI18nKey } from "src/helpers/utils";

const { t } = useI18n();

const statsLoading = ref(true);
const stats = ref({});
const activeCard = ref(null);

const statCards = [
  { key: "total_associados",     icon: "mdi-account-group",  labelKey: "dashboard.stats.total_associados" },
  { key: "associados_ativos",    icon: "mdi-trending-up",    labelKey: "dashboard.stats.associados_ativos" },
  { key: "parceiros",            icon: "mdi-handshake",      labelKey: "dashboard.stats.parceiros" },
  { key: "contratos_a_vencer",   icon: "mdi-file-clock",     labelKey: "dashboard.stats.contratos_a_vencer" },
  { key: "novos_mes",            icon: "mdi-account-plus",   labelKey: "dashboard.stats.novos_mes" },
  { key: "associados_pendentes", icon: "mdi-account-alert",  labelKey: "dashboard.stats.associados_pendentes" },
  { key: "ultimos_acessos",      icon: "mdi-login-variant",  labelKey: "dashboard.stats.ultimos_acessos" },
];

// Colunas por tipo de card
const columnsAssociados = computed(() => [
  { name: "name",       label: t("common.terms.name"),                field: "name",       align: "left", sortable: true },
  { name: "email",      label: t("common.terms.email"),               field: "email",      align: "left", sortable: true },
  { name: "created_at", label: t("dashboard.stats.association_date"), field: (row) => formatDateYMDtoDMY(row.created_at), align: "left", sortable: true },
  { name: "status",     label: t("common.terms.status"),              field: "status",     align: "left" },
]);

const columnsParceiros = computed(() => [
  { name: "company_name", label: t("common.terms.name"),                field: "company_name", align: "left", sortable: true },
  { name: "responsible",  label: t("parceiro.responsible"),             field: "responsible",  align: "left", sortable: true },
  { name: "created_at",   label: t("dashboard.stats.registration_date"), field: (row) => formatDateYMDtoDMY(row.created_at), align: "left", sortable: true },
  { name: "status",       label: t("common.terms.status"),              field: "status",       align: "left" },
]);

const columnsContratosAVencer = computed(() => [
  { name: "company_name", label: t("common.terms.name"),       field: "company_name",  align: "left", sortable: true },
  { name: "responsible",  label: t("parceiro.responsible"),     field: "responsible",   align: "left", sortable: true },
  { name: "contract_end", label: t("parceiro.contract_end"),    field: (row) => formatDateYMDtoDMY(row.contract_end), align: "left", sortable: true },
  { name: "status",       label: t("common.terms.status"),     field: "status",        align: "left" },
]);

const columnsAccessLogs = computed(() => [
  { name: "user_name",   label: t("access_log.user"),        field: "user_name",   align: "left",   sortable: false },
  { name: "user_type",   label: t("access_log.user_type"),   field: "user_type",   align: "center", sortable: false },
  { name: "accessed_at", label: t("access_log.accessed_at"), field: "accessed_at", align: "left",   sortable: false },
]);

const tableColumns = computed(() => {
  if (!activeCard.value) return [];
  if (activeCard.value === "contratos_a_vencer") return columnsContratosAVencer.value;
  if (activeCard.value === "parceiros" || activeCard.value === "novos_mes") return columnsParceiros.value;
  if (activeCard.value === "ultimos_acessos") return columnsAccessLogs.value;
  return columnsAssociados.value;
});

// Função de API correspondente a cada card — nova referência a cada computed
const activeApiCall = computed(() => {
  switch (activeCard.value) {
    case "total_associados":
      return (p) => getUsersPaginated({ ...p, type: "associado" });
    case "associados_ativos":
      return (p) => getUsersPaginated({ ...p, type: "associado", status: "active" });
    case "associados_pendentes":
      return (p) => getUsersPaginated({ ...p, type: "associado", status: "pending" });
    case "parceiros":
      return (p) => getPartnerAgreementsPaginated({ ...p });
    case "contratos_a_vencer":
      return (p) => getExpiringPartnerAgreementsPaginated({ ...p });
    case "novos_mes":
      return (p) => getPartnerAgreementsPaginated({ ...p, createdMonth: "current" });
    case "ultimos_acessos":
      return (p) => getAccessLogsPaginated({ ...p, last_per_user: true });
    default:
      return null;
  }
});

const formatDateTime = (isoString) => {
  if (!isoString) return "—";
  const d = new Date(isoString);
  return d.toLocaleString("pt-BR", {
    day: "2-digit", month: "2-digit", year: "numeric",
    hour: "2-digit", minute: "2-digit", second: "2-digit",
  });
};

const onCardClick = (card) => {
  activeCard.value = activeCard.value === card.key ? null : card.key;
};

onMounted(async () => {
  try {
    stats.value = await getDashboardStats();
  } finally {
    statsLoading.value = false;
  }
});
</script>

<style scoped>
.stat-card {
  border-radius: 12px;
  border: 2px solid transparent;
  transition: box-shadow 0.2s, border-color 0.2s, background-color 0.2s;
}

.stat-card:hover {
  box-shadow: 0 2px 8px rgba(102, 29, 117, 0.15);
}

.stat-card--active {
  border-color: #4d1658;
  background-color: #f0e8f1 !important;
  box-shadow: 0 2px 12px rgba(77, 22, 88, 0.18);
}
</style>
