<template>
  <section-wrapper class="bg-background-3">
    <section-container
      mobile-padding
      class="max-w-container pb-8 pt-8 max-xl:text-center max-md:hidden"
    >
      <div v-if="loading" class="grid-cols-4 gap-5 max-lg:grid-cols-2 md:grid">
        <Skeleton height="13rem" class="w-full" borderRadius="16px"></Skeleton>
        <Skeleton height="13rem" class="w-full" borderRadius="16px"></Skeleton>
        <Skeleton height="13rem" class="w-full" borderRadius="16px"></Skeleton>
        <Skeleton height="13rem" class="w-full" borderRadius="16px"></Skeleton>
      </div>

      <div v-else class="grid-cols-4 gap-5 max-lg:grid-cols-2 md:grid">
        <div
          v-for="(stat, index) in computedStats"
          :key="index"
          class="flex bg-white max-md:items-center max-md:gap-3 max-md:p-3 md:flex-col md:p-8"
        >
          <icon class="text-secondary mb-6 h-8 w-8" :icon="stat.icon"></icon>

          <div class="text-primary mb-2 text-[1.875rem] font-semibold">
            {{ stat.count }}
          </div>
          <div class="text-[#707070]">{{ stat.title }}</div>
        </div>
      </div>
    </section-container>
  </section-wrapper>
</template>
<script setup>
const stats = ref({});
const loading = ref(false);

const computedStats = computed(() => {
  return [
    {
      icon: "pin-2",
      title: "Trajets disponibles sur la plateforme",
      count: stats.value?.total_available_routes ?? 0,
    },
    {
      icon: "pin-2",
      title: "Total des trajets proposés sur la plateforme",
      count: stats.value?.total_created_routes ?? 0,
    },
    {
      icon: "pin-2",
      title: "Mes trajets en ligne",
      count: stats.value?.company_available_routes ?? 0,
    },
    {
      icon: "pin-2",
      title: "Mes trajets effectués",
      count: stats.value?.company_finished_route ?? 0,
    },
  ];
});

const { $api, $listen, $unListen } = useNuxtApp();

const fetchStats = async () => {
  loading.value = true;

  $api
    .call("get", $api.route("me.company.stats"))
    .then((result) => {
      stats.value = result;
      loading.value = false;
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  fetchStats();

  $listen("refresh-all", fetchStats);
});

onBeforeUnmount(() => {
  $unListen("refresh-all", fetchStats);
});
</script>
