import { computed, ref } from "vue";
import { getOwnerDashboard } from "src/api/ownerDashboard";

export function useOwnerDashboard() {
  const dashboard = ref(null);
  const loading = ref(false);
  const revenueSeries = ref([]);

  const summary = computed(() => dashboard.value?.summary ?? {});
  const channels = computed(() => dashboard.value?.channels ?? []);

  const availableReferences = computed(
    () => dashboard.value?.filters?.available_references ?? [],
  );

  const selectedFilters = computed(
    () => dashboard.value?.filters?.selected ?? {},
  );

  const fetchDashboard = async (params = {}) => {
    loading.value = true;

    try {
      const payload = await getOwnerDashboard(params);

      dashboard.value = payload;

      await fetchRevenueHistory(payload);
    } finally {
      loading.value = false;
    }
  };

  const fetchRevenueHistory = async (payload) => {
    const references = (payload?.filters?.available_references ?? [])
      .slice(0, 6)
      .reverse();

    if (!references.length) {
      revenueSeries.value = [];

      return;
    }

    try {
      const propertyId = payload?.filters?.selected?.property_id ?? null;

      const responses = await Promise.all(
        references.map(async (reference) => {
          const historyPayload = await getOwnerDashboard({
            year: reference.reference_year,
            month: reference.reference_month,
            property_id: propertyId,
          });

          return {
            label: new Intl.DateTimeFormat("pt-BR", {
              month: "short",
            })
              .format(
                new Date(
                  reference.reference_year,
                  reference.reference_month - 1,
                  1,
                ),
              )
              .replace(".", ""),
            value: Number(historyPayload?.summary?.reserve_total ?? 0),
          };
        }),
      );

      revenueSeries.value = responses;
    } catch {
      revenueSeries.value = [];
    }
  };

  return {
    availableReferences,
    channels,
    dashboard,
    loading,
    revenueSeries,
    selectedFilters,
    summary,
    fetchDashboard,
  };
}
