<template>
  <div>
    <DefaultHeaderPage
      title="Dashboard"
      :filter-open="showFilter"
      @show-filter="showFilter = !showFilter"
    />

    <div class="q-pa-sm">
      <div class="filter-row">
        <template v-if="showFilter">
          <UnitSelect
            v-model="selectedUnit"
            dense
            label="Unidade"
            class="filter-item"
            color="secondary"
          />

          <DefaultSelect
            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"
          />

          <template v-if="selectedPeriod === 'custom'">
            <DefaultInputDatePicker
              v-model="startDate"
              dense
              label="Data Inicial"
              color="secondary"
              class="filter-item"
            />

            <DefaultInputDatePicker
              v-model="endDate"
              dense
              label="Data Final"
              color="secondary"
              class="filter-item"
            />
          </template>
        </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="totalStudents"
          :badge="`${activeContracts} ativos`"
          clickable
          @click="openActiveStudentsDialog"
        />
        <DashboardStatCard
          title="Contratos Congelados"
          icon="mdi-snowflake"
          :value="frozenContracts"
          subtitle="É hora de incentivar nossos alunos"
          clickable
          @click="openFrozenContractsDialog"
        />
        <DashboardStatCard
          title="Contratos Cancelados"
          icon="mdi-cancel"
          :value="cancelledContracts"
          subtitle="É hora de incentivar nossos alunos"
          clickable
          @click="openCancelledContractsDialog"
        />
        <DashboardStatCard
          title="Receita Geral"
          icon="mdi-currency-usd"
          value="R$ 0,00"
          subtitle="0 pagamentos pendentes"
        />
      </div>

      <div class="stat-cards-row">
        <DashboardStatCard
          title="Frequência Média"
          icon="mdi-account-multiple-outline"
          value="0%"
          clickable
          @click="openAverageAttendanceDialog"
        />
        <DashboardStatCard
          title="Estoque Geral de Produtos"
          icon="mdi-currency-usd"
          value="0"
          clickable
          @click="openProductStockDialog"
        />
        <DashboardStatCard
          title="Tarefas Pendentes"
          icon="mdi-draw"
          value="0"
          subtitle="Não deixe para amanhã"
        />
        <DashboardStatCard
          title="Tickets Abertos"
          icon="mdi-calendar-outline"
          value="0"
          subtitle="Estável"
          clickable
          @click="openTicketsDialog"
        />
      </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>

        <HolidaysCard />
        <BirthdaysCard :people="birthdays" />
      </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 DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";
import UnitSelect from "src/components/selects/UnitSelect.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 BirthdaysCard from "src/components/charts/BirthdaysCard.vue";
import HolidaysCard from "src/components/charts/HolidaysCard.vue";
import ActiveStudentsDialog from "src/pages/dashboard/components/ActiveStudentsDialog.vue";
import { getStudentSummaryFranchisor } from "src/api/student";
import { getFranchisorContractSummary } from "src/api/student_contract";
import FrozenContractsDialog from "src/pages/dashboard/components/FrozenContractsDialog.vue";
import CancelledContractsDialog from "src/pages/dashboard/components/CancelledContractsDialog.vue";
import AverageAttendanceDialog from "src/pages/dashboard/components/AverageAttendanceDialog.vue";
import ProductStockDialog from "src/pages/dashboard/components/ProductStockDialog.vue";
import OpenTicketsDialog from "src/pages/dashboard/components/OpenTicketsDialog.vue";

const { t } = useI18n();

const $q = useQuasar();

const isLoading = ref(true);

const totalStudents = ref(0);
const activeContracts = ref(0);
const frozenContracts = ref(0);
const cancelledContracts = ref(0);

const openActiveStudentsDialog = () => {
  $q.dialog({ component: ActiveStudentsDialog });
};

const openFrozenContractsDialog = () => {
  $q.dialog({ component: FrozenContractsDialog });
};

const openCancelledContractsDialog = () => {
  $q.dialog({ component: CancelledContractsDialog });
};

const openAverageAttendanceDialog = () => {
  $q.dialog({ component: AverageAttendanceDialog });
};

const openProductStockDialog = () => {
  $q.dialog({ component: ProductStockDialog });
};

const openTicketsDialog = () => {
  $q.dialog({ component: OpenTicketsDialog });
};
const defaultPeriod = ref("month");
const defaultEventId = ref(1);

const showFilter = ref(false);
const selectedUnit = ref(null);
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 birthdays = [
  { 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 () => {
  getStudentSummaryFranchisor().then((summary) => {
    totalStudents.value = summary.total;
    activeContracts.value = summary.active;
  });
  getFranchisorContractSummary().then((summary) => {
    frozenContracts.value = summary.frozen;
    cancelledContracts.value = summary.cancelled;
  });
  await updateDashboardData();
});
</script>

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

.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(55.5556% - 8px);
  min-width: 0;
}

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

.charts-row > *:nth-child(3),
.charts-row > *:nth-child(4) {
  flex: 1 1 calc(50% - 8px);
  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>
