<template>
  <div>
    <DefaultHeaderPage class="q-pa-sm" />

    <div class="q-pa-sm">
      <div class="stat-cards-row q-mb-md">
        <DashboardStatCard
          title="Total alunos (contratos ativos)"
          icon="mdi-account-multiple-outline"
          :value="String(totalAlunos)"
          :badge="`${totalAlunos} ativos`"
        />
        <DashboardStatCard
          title="Receita Total"
          icon="mdi-currency-usd"
          value="R$ 0,00"
          subtitle="0 pagamentos pendentes"
        />
        <DashboardStatCard
          title="Ticket Médio"
          icon="mdi-calendar-blank"
          value="R$ 12,00"
          subtitle="Estável"
        />
        <DashboardStatCard
          title="Aniversariantes"
          icon="mdi-emoticon-happy-outline"
          value="0"
          subtitle="Fortaleça seus relacionamentos"
        />
      </div>

      <div class="row q-col-gutter-md q-mb-md items-stretch">
        <div class="col-12 col-md-5">
          <DashboardChartCard title="Faturamento Serviço / Materiais" style="height: 100%">
            <GroupedBarChart
              :labels="faturamentoChart.labels"
              :datasets="faturamentoChart.datasets"
              label-y="R$"
              :tick-formatter="formatCurrencyTick"
              :tooltip-formatter="formatCurrencyTooltip"
              class="full-width full-height"
            />
          </DashboardChartCard>
        </div>

        <div class="col-12 col-md-4">
          <q-card flat bordered class="full-height">
            <q-card-section class="row justify-between items-center q-pb-xs">
              <span class="text-subtitle2 text-weight-medium"
                >Contratos Ativos</span
              >
              <q-icon name="mdi-trending-up" color="grey-5" />
            </q-card-section>
            <q-separator />
            <q-card-section
              class="flex flex-center q-pt-sm"
              style="height: calc(100% - 57px); position: relative"
            >
              <div style="height: 100%; max-width: 280px; width: 100%">
                <Doughnut
                  :data="gaugeData"
                  :options="gaugeOptions"
                  :plugins="[gaugeNeedlePlugin]"
                />
              </div>
              <div class="gauge-label">
                <div class="text-h5 text-bold">70</div>
                <div class="text-caption text-grey-6">Grade</div>
              </div>
            </q-card-section>
          </q-card>
        </div>

        <div class="col-12 col-md-3">
          <q-card flat bordered class="full-height">
            <q-card-section class="row justify-between items-center q-pb-xs">
              <span class="text-subtitle2 text-weight-medium"
                >Atalhos rápidos</span
              >
              <q-icon name="mdi-apps" color="grey-5" />
            </q-card-section>
            <q-separator />
            <q-card-section class="q-pt-md column q-gutter-sm">
              <q-btn
                unelevated
                color="primary"
                label="Criar contrato"
                no-caps
                class="full-width"
              />
              <q-btn
                unelevated
                color="primary"
                label="Registrar presença"
                no-caps
                class="full-width"
              />
              <q-btn
                unelevated
                color="primary"
                label="Novo pedido"
                no-caps
                class="full-width"
              />
            </q-card-section>
          </q-card>
        </div>
      </div>

      <!-- Row 3: Bottom -->
      <div class="row q-col-gutter-md items-stretch">
        <div class="col-12 col-md-5">
          <q-card flat class="card-ring full-height feriados-card">
            <div class="flex justify-between items-center no-wrap q-mb-sm">
              <span class="text-subtitle2 text-weight-regular">Feriados do mês</span>
              <q-btn
                flat
                round
                dense
                icon="mdi-calendar-star"
                color="grey-5"
                @click="openFeriadosDialog"
              />
            </div>

            <q-btn
              unelevated
              color="primary"
              label="Nova data"
              no-caps
              class="full-width q-mb-md"
              @click="openFeriadosDialog"
            />

            <div v-if="feriadosLoading" class="flex flex-center q-py-md">
              <q-spinner color="primary" size="24px" />
            </div>
            <div v-else-if="feriadosMes.length === 0" class="text-caption text-grey-5 text-center q-mt-sm">
              Nenhum feriado neste mês.
            </div>
            <div v-else class="row q-gutter-sm">
              <div
                v-for="feriado in feriadosMes"
                :key="feriado.id"
                class="column items-center cursor-pointer"
                style="min-width: 52px"
                @click="openEditFromDashboard(feriado)"
              >
                <q-badge
                  color="deep-orange"
                  class="text-subtitle1 text-bold q-pa-sm"
                  style="min-width: 40px; justify-content: center"
                >
                  {{ feriado.dia }}
                </q-badge>
                <div class="text-caption q-mt-xs text-center">
                  {{ feriado.nome }}
                </div>
              </div>
            </div>
          </q-card>
        </div>

        <div class="col-12 col-md-4">
          <DashboardChartCard title="Matrículas por Período" style="height: 100%">
            <GroupedBarChart
              :labels="matriculasChart.labels"
              :datasets="matriculasChart.datasets"
              :bar-radius="50"
              :show-datalabels="true"
              :max-bar-thickness="44"
              :category-percentage="0.6"
              :bar-percentage="0.85"
              class="full-width full-height"
            />
          </DashboardChartCard>
        </div>

        <div class="col-12 col-md-3">
          <AniversariantesCard :people="aniversariantes" style="height: 100%" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { Doughnut } from "vue-chartjs";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { useQuasar } from "quasar";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DashboardStatCard from "src/components/charts/DashboardStatCard.vue";
import DashboardChartCard from "src/components/charts/DashboardChartCard.vue";
import GroupedBarChart from "src/components/charts/normal/GroupedBarChart.vue";
import AniversariantesCard from "src/components/charts/AniversariantesCard.vue";
import FeriadosDialog from "./components/FeriadosDialog.vue";
import FeriadosEditDialog from "./components/FeriadosEditDialog.vue";
import { getHolidays } from "src/api/holiday";
import { getStudents } from "src/api/student";
import { userStore } from "src/stores/user";

ChartJS.register(ArcElement, Tooltip, Legend);

const $q = useQuasar();
const store = userStore();

const faturamentoChart = {
  labels: [
    "17/02", "18/02", "19/02", "20/02", "21/02",
    "22/02", "23/02", "24/02", "25/02", "26/02",
    "27/02", "28/02",
  ],
  datasets: [
    {
      label: "Serviço",
      data: [120, 185, 95, 210, 155, 200, 170, 130, 195, 160, 145, 180],
      color: "#a274f1",
    },
    {
      label: "Materiais",
      data: [75, 115, 60, 140, 95, 125, 105, 85, 135, 100, 90, 115],
      color: "#ff9999",
    },
  ],
};

const formatCurrencyTick = (value) => {
  if (value >= 1000) return `R$ ${(value / 1000).toFixed(0)}k`;
  return `R$ ${value}`;
};

const formatCurrencyTooltip = (context) => {
  const value = context.parsed.y;
  return ` ${context.dataset.label}: R$ ${value.toLocaleString("pt-BR", { minimumFractionDigits: 2 })}`;
};

const gaugeData = ref({
  datasets: [
    {
      backgroundColor: [
        "#00a550",
        "#4dbb7e",
        "#9ad2ad",
        "#cce156",
        "#fff100",
        "#ffbe00",
        "#ff8c00",
        "#FC3D23",
        "#D01616",
        "#8A0000",
      ],
      data: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
      needleValue: 7,
      borderColor: "transparent",
    },
  ],
});

const gaugeOptions = ref({
  rotation: 270,
  circumference: 180,
  cutout: "50%",
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    tooltip: { enabled: false },
    legend: { display: false },
    datalabels: {
      color: "black",
      font: { size: 14, weight: "bold" },
      formatter: (_value, ctx) => ctx.dataIndex,
    },
  },
});

const gaugeNeedlePlugin = {
  id: "gaugeNeedle",
  afterDatasetsDraw(chart) {
    const { ctx, data } = chart;
    ctx.save();
    const needleValue = data.datasets[0].needleValue;
    const meta = chart.getDatasetMeta(0).data[0];
    const xCenter = meta.x;
    const yCenter = meta.y;
    const outerRadius = meta.outerRadius - 20;
    const circumference =
      (meta.circumference / Math.PI / data.datasets[0].data[0]) * needleValue;
    const angle = Math.PI;
    ctx.translate(xCenter, yCenter);
    ctx.rotate(angle * (circumference + 1.5));
    ctx.beginPath();
    ctx.strokeStyle = "grey";
    ctx.fillStyle = "grey";
    ctx.moveTo(-3, 0);
    ctx.lineTo(0, -outerRadius);
    ctx.lineTo(3, 0);
    ctx.stroke();
    ctx.fill();
    ctx.beginPath();
    ctx.arc(0, 0, 6, 0, 2 * Math.PI);
    ctx.fillStyle = "grey";
    ctx.fill();
    ctx.restore();
  },
};

const matriculasChart = {
  labels: ["JAN", "FEV", "MAR", "ABR", "MAI", "JUN"],
  datasets: [
    {
      label: "Matrículas",
      data: [120, 200, 150, 80, 70, 110],
      color: ["#3B82F6", "#EF4444", "#A855F7", "#374151", "#EAB308", "#06B6D4"],
    },
  ],
};

const aniversariantes = ref([
  { day: 10, name: "Heloisa Faria" },
  { day: 11, name: "Juliana Costa" },
  { day: 16, name: "Juliana Costa" },
  { day: 23, name: "Fernando Almeida" },
  { day: 29, name: "Lucas Pereira" },
  { day: 34, name: "Sofia Martins" },
]);

// Alunos
const totalAlunos = ref(0);

async function fetchAlunos() {
  try {
    const students = await getStudents();
    totalAlunos.value = students.length;
  } catch {
    // silencioso
  }
}

// Feriados
const allHolidays = ref([]);
const feriadosLoading = ref(false);

const feriadosMes = computed(() => {
  const now = new Date();
  const month = now.getMonth() + 1;
  const year = now.getFullYear();
  return allHolidays.value
    .filter((h) => {
      const d = new Date(h.holiday_date + "T00:00:00");
      return d.getMonth() + 1 === month && d.getFullYear() === year;
    })
    .sort((a, b) => new Date(a.holiday_date) - new Date(b.holiday_date))
    .map((h) => ({
      id: h.id,
      dia: new Date(h.holiday_date + "T00:00:00").getDate(),
      nome: h.description,
      holiday_date: h.holiday_date,
      description: h.description,
      type: h.type,
      base_holiday_id: h.base_holiday_id ?? null,
    }));
});

async function fetchHolidays() {
  feriadosLoading.value = true;
  try {
    allHolidays.value = await getHolidays();
  } catch {
    $q.notify({ type: "negative", message: "Erro ao carregar feriados." });
  } finally {
    feriadosLoading.value = false;
  }
}

function openFeriadosDialog() {
  $q.dialog({ component: FeriadosDialog }).onOk(() => {
    fetchHolidays();
  });
}

function openEditFromDashboard(feriado) {
  $q.dialog({
    component: FeriadosEditDialog,
    componentProps: { holiday: feriado },
  }).onOk(({ action, holiday: updated, id }) => {
    if (action === "update") {
      const idx = allHolidays.value.findIndex((h) => h.id === updated.id);
      if (idx !== -1) allHolidays.value[idx] = { ...allHolidays.value[idx], ...updated };
    } else if (action === "delete") {
      allHolidays.value = allHolidays.value.filter((h) => h.id !== id);
    }
  });
}

// Recarrega dados do dashboard quando a unidade ativa mudar
watch(
  () => store.selectedUnit?.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      fetchAlunos();
      fetchHolidays();
    }
  },
);

onMounted(() => {
  fetchHolidays();
  fetchAlunos();
});
</script>

<style scoped>
.stat-cards-row {
  display: flex;
  flex-wrap: nowrap;
  gap: 16px;
}

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

@media (max-width: 599px) {
  .stat-cards-row {
    flex-wrap: wrap;
  }
  .stat-cards-row > * {
    flex: 1 1 calc(50% - 8px);
  }
}

.gauge-label {
  position: absolute;
  bottom: 28%;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  pointer-events: none;
}

.feriados-card {
  border-radius: 12px;
  padding: 20px 24px;
  display: flex;
  flex-direction: column;
}
</style>
