import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import axiosInstance from "@/lib/axios";

const fetchAdminStatsBasic = async () => {
  const { data } = await axiosInstance.get(`/superadmin/dashboard-stats`);

  return data;
};

const fetchCustomers = async (page: number) => {
  const { data } = await axiosInstance.get(
    `/superadmin/dashboard-user-list?page=${page}`
  );

  return data;
};

const fetchDeletedCustomers = async (page: number) => {
  const { data } = await axiosInstance.get(
    `/superadmin/dashboard-user-list-deleted?page=${page}`
  );

  return data;
};

const fetchProfilePersona = async (userId: string) => {
  const { data } = await axiosInstance.get(`/users/${userId}/personal-profile`);

  return data;
};

const fetchMonthlyStats = async (month: number, year?: string) => {
  const query = `/superadmin/dashboard-stats-monthly?${
    year ? `year=${year}&month=${month}` : `month=${month}`
  }`;

  const { data } = await axiosInstance.get(query);
  return data;
};

const fetchYearlyStats = async (year: string | undefined) => {
  const { data } = await axiosInstance.get(
    `/superadmin/dashboard-stats-yearly?year=${year}`
  );

  return data;
};

export const useGetStats = () => {
  return useQuery({
    queryKey: ["BasicStatData"],
    queryFn: fetchAdminStatsBasic,
    staleTime: 1000 * 60 * 10,
    refetchOnWindowFocus: true,
  });
};

export const useGetCustomers = (page: number = 1) => {
  return useQuery({
    queryKey: ["CustomersData", page],
    queryFn: () => fetchCustomers(page),
    staleTime: 1000 * 60 * 10,
  });
};

export const useGetDeletedCustomers = (page: number = 1) => {
  return useQuery({
    queryKey: ["DeletedCustomersData", page],
    queryFn: () => fetchDeletedCustomers(page),
    staleTime: 1000 * 60 * 10,
  });
};

export const useGetCustomersProfilePersona = (userId: string) => {
  return useQuery({
    queryKey: ["ProfilePersona", userId],
    queryFn: () => fetchProfilePersona(userId),
    staleTime: 1000 * 60 * 10,
  });
};

export const useGetMonthlyGraphData = (year?: string) => {
  const currentMonth = new Date().getMonth();
  const [selectedMonth, setSelectedMonth] = useState(currentMonth + 1);

  const { data, refetch } = useQuery({
    queryKey: ["monthlyStats", selectedMonth, year],
    queryFn: () => fetchMonthlyStats(selectedMonth, year),
    staleTime: 1000 * 60 * 10,
  });

  return { data, selectedMonth, setSelectedMonth, refetch };
};

export const useGetYearlyGraphData = (year?: string) => {
  return useQuery({
    queryKey: ["yearlyStats"],
    queryFn: () => fetchYearlyStats(year),
    staleTime: 1000 * 60 * 10,
  });
};
