import { useState } from "react";
import {
  getDashboardData,
  type DashboardResponse,
} from "../../services/dashboardService";
import { handleToastError } from "../../utils";

function useDashboardService() {
  const [loading, setLoading] = useState(false);

  // Get Dashboard Data
  const getDashboardDataAsync = async () => {
    try {
      setLoading(true);
      const response = await getDashboardData();

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data.data,
          message:
            response.data.message || "Dashboard data loaded successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response?.data?.message || "Failed to load dashboard data";
        handleToastError(errorMessage);
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      handleToastError(errorMessage);
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    getDashboardData: getDashboardDataAsync,
  };
}

export default useDashboardService;
