<template>
  <div>
    <DefaultHeaderPage show-filter-icon class="q-pa-sm">
      <template #after>
        <div class="flex items-center no-wrap" style="gap: 12px">
          <q-select
            v-if="$q.screen.gt.xs"
            v-model="selectedUnit"
            dense
            :options="[]"
            label="Unidade"
            style="width: 250px; flex-shrink: 0"
            color="secondary"
            hide-dropdown-icon
          >
            <template #append>
              <q-icon name="mdi-map-marker-outline" color="secondary" />
            </template>
          </q-select>

          <div
            class="flex items-center no-wrap q-gutter-x-md q-px-sm q-ml-md"
            style="flex-shrink: 0"
          >
            <q-img src="icons/user-icon.jpg" class="avatar-circle" />

            <div
              v-if="$q.screen.gt.xs"
              class="column q-gutter-y-none"
              style="white-space: nowrap"
            >
              <span class="text-body2 text-center">Ana Laura</span>
              <span
                v-if="$q.screen.gt.sm"
                class="text-overline text-center"
                style="line-height: 1rem; font-weight: 400"
                >Gerente</span
              >
            </div>
          </div>

          <template v-if="$q.screen.gt.sm">
            <q-separator
              vertical
              style="height: 36px; width: 2px; flex-shrink: 0"
              color="dark"
            />

            <div
              class="column"
              style="line-height: 1.2; white-space: nowrap; flex-shrink: 0"
            >
              <span class="text-caption text-grey-6 text-primary text-center"
                >Ultimo acesso</span
              >
              <span class="text-caption text-primary text-center"
                >16/02/2026, 14:16</span
              >
            </div>
          </template>

          <div
            class="flex items-center no-wrap"
            style="gap: 2px; flex-shrink: 0"
          >
            <q-btn flat round dense icon="mdi-bell-badge" color="secondary" />
            <q-btn flat round dense icon="mdi-account" color="secondary" />
            <q-btn flat round dense icon="mdi-cog-outline" color="secondary" />
          </div>
        </div>
      </template>
    </DefaultHeaderPage>

    <div class="q-pa-sm">
      <div class="filter-row">
        <q-select
          v-model="selectedPeriod"
          :options="periodOptions"
          option-value="value"
          option-label="label"
          emit-value
          map-options
          dense
          label="Selecione o Período"
          color="secondary"
          class="filter-item"
          hide-dropdown-icon
        >
          <template #append>
            <q-icon name="mdi-chevron-down" color="secondary" />
          </template>
        </q-select>

        <template v-if="selectedPeriod === 'custom'">
          <q-input
            v-model="startDate"
            dense
            label="Data Inicial"
            mask="##/##/####"
            placeholder="DD/MM/AAAA"
            color="secondary"
            class="filter-item"
          >
            <template #append>
              <q-icon
                name="mdi-calendar"
                color="secondary"
                class="cursor-pointer"
              >
                <q-popup-proxy
                  cover
                  transition-show="scale"
                  transition-hide="scale"
                >
                  <q-date
                    v-model="startDate"
                    mask="DD/MM/YYYY"
                    color="secondary"
                  >
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="OK" color="secondary" flat />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>

          <q-input
            v-model="endDate"
            dense
            label="Data Final"
            mask="##/##/####"
            placeholder="DD/MM/AAAA"
            color="secondary"
            class="filter-item"
          >
            <template #append>
              <q-icon
                name="mdi-calendar"
                color="secondary"
                class="cursor-pointer"
              >
                <q-popup-proxy
                  cover
                  transition-show="scale"
                  transition-hide="scale"
                >
                  <q-date v-model="endDate" mask="DD/MM/YYYY" color="secondary">
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="OK" color="secondary" flat />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </template>
      </div>
    </div>

    <div v-if="!isLoading" class="column gap q-pa-sm">
      <div class="stat-cards-row">
        <DashboardStatCard
          title="Total alunos (contratos ativos)"
          icon="mdi-account-multiple-outline"
          value="4.527"
          badge="3.200 ativos"
          clickable
          @click="openAlunosDialog"
        />
        <DashboardStatCard
          title="Contratos Congelados"
          icon="mdi-snowflake"
          value="57"
          subtitle="É hora de incentivar nossos alunos"
          clickable
          @click="openContratosCongeladosDialog"
        />
        <DashboardStatCard
          title="Contratos Cancelados"
          icon="mdi-cancel"
          value="57"
          subtitle="É hora de incentivar nossos alunos"
        />
        <DashboardStatCard
          title="Receita Geral"
          icon="mdi-currency-usd"
          value="R$ 51.548,80"
          subtitle="0 pagamentos pendentes"
        />
      </div>

      <div class="charts-row">
        <DashboardChartCard title="Faturamento Serviço / Materiais">
          <GroupedBarChart
            :labels="faturamentoChart.labels"
            :datasets="faturamentoChart.datasets"
            label-y="R$"
            :tick-formatter="formatCurrencyTick"
            :tooltip-formatter="formatCurrencyTooltip"
            class="full-width full-height"
          />
        </DashboardChartCard>

        <DashboardChartCard title="Matrículas por Período">
          <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>

        <AniversariantesCard :people="aniversariantes" />
      </div>

      <div class="stat-cards-row">
        <DashboardStatCard
          title="Frequência Média"
          icon="mdi-account-multiple-outline"
          value="87%"
          badge="Alta"
          badge-color="approved"
          custom-style="padding: 6px 24px"
        />
        <DashboardStatCard
          title="Estoque Geral de Produtos"
          icon="mdi-currency-usd"
          value="56"
        />
        <DashboardStatCard
          title="Tarefas Pendentes"
          icon="mdi-draw"
          value="4"
          subtitle="Não deixe para amanhã"
        />
        <DashboardStatCard
          title="Tickets Abertos"
          icon="mdi-calendar-outline"
          value="2"
          subtitle="Estável"
        />
      </div>
    </div>

    <div v-else class="flex flex-center full-width q-pa-xl">
      <q-spinner color="primary" size="50px" />
    </div>

  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
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 AlunosAtivosDialog from "src/pages/dashboard/components/AlunosAtivosDialog.vue";
import ContratosCongeladosDialog from "src/pages/dashboard/components/ContratosCongeladosDialog.vue";

const { t } = useI18n();

const $q = useQuasar();
const isLoading = ref(true);

const openAlunosDialog = () => {
  $q.dialog({ component: AlunosAtivosDialog });
};

const openContratosCongeladosDialog = () => {
  $q.dialog({ component: ContratosCongeladosDialog });
};
const selectedUnit = ref(null);
const defaultPeriod = ref("month");
const defaultEventId = ref(1);

const selectedPeriod = ref("custom");
const startDate = ref("");
const endDate = ref("");

const periodOptions = [
  { label: "Hoje", value: "today" },
  { label: "Esta semana", value: "week" },
  { label: "Este mês", value: "month" },
  { label: "Este ano", value: "year" },
  { label: "Personalizado", value: "custom" },
];

const aniversariantes = [
  { 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" },
];

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 faturamentoChart = {
  labels: [
    "17/02",
    "18/02",
    "19/02",
    "20/02",
    "21/02",
    "22/02",
    "23/02",
    "24/02",
    "25/02",
    "26/02",
  ],
  datasets: [
    {
      label: "Serviço",
      data: [
        18500, 21000, 16400, 22300, 19800, 17200, 15800, 24100, 20500, 27600,
      ],
      color: "#a274f1",
    },
    {
      label: "Materiais",
      data: [9200, 10500, 8100, 11400, 9800, 8400, 8700, 12200, 10100, 13100],
      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 ordersChart = ref({});
const participantsChart = ref({});
const paymentsChart = ref({});
const ticketsSoldChart = ref({});
const eventTicketsByTypeChart = ref({});
const eventParticipantsByCNPJAndCPF = ref({});
const salesOverTimeLineChart = ref({});
const eventSourcePieChart = ref({});

const generateMockData = () => {
  const createMiniChartData = (currentTotal, percentage) => ({
    current_total: currentTotal,
    percentage_change: percentage,
    trend_data: Array.from({ length: 10 }, () =>
      Math.floor(Math.random() * 100),
    ),
  });

  const barChartDataRaw = [
    {
      label: t("dashboard.charts.tickets_by_type.labels.vip"),
      value: Math.floor(Math.random() * 300),
    },
    {
      label: t("dashboard.charts.tickets_by_type.labels.track"),
      value: Math.floor(Math.random() * 800),
    },
    {
      label: t("dashboard.charts.tickets_by_type.labels.box"),
      value: Math.floor(Math.random() * 400),
    },
    {
      label: t("dashboard.charts.tickets_by_type.labels.courtesy"),
      value: Math.floor(Math.random() * 50),
    },
  ];

  const doughnutDataRaw = [
    {
      label: t("common.terms.cpf"),
      value: Math.floor(Math.random() * 900 + 100),
    },
    {
      label: t("common.terms.cnpj"),
      value: Math.floor(Math.random() * 100 + 10),
    },
  ];
  const doughnutTotal = doughnutDataRaw.reduce(
    (sum, item) => sum + item.value,
    0,
  );

  const lineChartDataRaw = [
    {
      label: t("common.months.january"),
      value: Math.floor(1200 + Math.random() * 500),
    },
    {
      label: t("common.months.february"),
      value: Math.floor(1900 + Math.random() * 500),
    },
    {
      label: t("common.months.march"),
      value: Math.floor(3000 + Math.random() * 500),
    },
    {
      label: t("common.months.april"),
      value: Math.floor(5000 + Math.random() * 500),
    },
    {
      label: t("common.months.may"),
      value: Math.floor(2300 + Math.random() * 500),
    },
    {
      label: t("common.months.june"),
      value: Math.floor(3200 + Math.random() * 500),
    },
  ];

  const pieDataRaw = [
    {
      label: t("dashboard.charts.registration_source.sources.instagram"),
      value: Math.floor(450 + Math.random() * 50),
    },
    {
      label: t("dashboard.charts.registration_source.sources.facebook"),
      value: Math.floor(250 + Math.random() * 50),
    },
    {
      label: t("dashboard.charts.registration_source.sources.google"),
      value: Math.floor(180 + Math.random() * 50),
    },
    {
      label: t("dashboard.charts.registration_source.sources.referral"),
      value: Math.floor(120 + Math.random() * 50),
    },
  ];
  const pieTotal = pieDataRaw.reduce((sum, item) => sum + item.value, 0);

  return {
    payments: createMiniChartData(
      (Math.random() * 20000 + 5000).toFixed(2),
      (Math.random() * 20 - 5).toFixed(2),
    ),
    orders: createMiniChartData(
      Math.floor(Math.random() * 500 + 50),
      (Math.random() * 15 - 5).toFixed(2),
    ),
    tickets_sold: createMiniChartData(
      Math.floor(Math.random() * 1500 + 200),
      (Math.random() * 25 - 5).toFixed(2),
    ),
    participants: createMiniChartData(
      Math.floor(Math.random() * 1000 + 100),
      (Math.random() * 10 - 5).toFixed(2),
    ),
    barData: {
      chart_data: barChartDataRaw,
    },
    doughnutData: {
      chart_data: doughnutDataRaw,
      current_total: doughnutTotal,
    },
    lineData: {
      chart_data: lineChartDataRaw,
    },
    pieData: {
      chart_data: pieDataRaw,
      current_total: pieTotal,
    },
  };
};

const updateDashboardData = async () => {
  isLoading.value = true;
  setTimeout(() => {
    const mockData = generateMockData();

    ordersChart.value = mockData.orders;
    participantsChart.value = mockData.participants;
    paymentsChart.value = mockData.payments;
    ticketsSoldChart.value = mockData.tickets_sold;

    eventTicketsByTypeChart.value = mockData.barData;
    eventParticipantsByCNPJAndCPF.value = mockData.doughnutData;
    salesOverTimeLineChart.value = mockData.lineData;
    eventSourcePieChart.value = mockData.pieData;

    isLoading.value = false;
  }, 500);
};

watch([defaultPeriod, defaultEventId], async () => {
  await updateDashboardData();
});

onMounted(async () => {
  await updateDashboardData();
});
</script>

<style scoped>
.gap {
  gap: 16px;
}

.avatar-circle {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  flex-shrink: 0;
}

.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);
  }
}

.charts-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.charts-row > *:nth-child(1) {
  flex: 0 0 calc(41.6667% - 11px);
  min-width: 0;
}

.charts-row > *:nth-child(2) {
  flex: 0 0 calc(33.3333% - 11px);
  min-width: 0;
}

.charts-row > *:nth-child(3) {
  flex: 0 0 calc(25% - 11px);
  min-width: 0;
}

@media (max-width: 599px) {
  .charts-row > * {
    flex: 1 1 100%;
  }
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.filter-item {
  flex: 1 1 200px;
  min-width: 180px;
  max-width: 300px;
}

@media (max-width: 599px) {
  .filter-item {
    flex: 1 1 100%;
    max-width: 100%;
  }
}
</style>
