// Import necessary modules and components
import { useEffect, useState } from "react";
import { SuperAdminSelectedPanel } from "../../core/constants/selected_panel";
import { useAuth } from "../../core/context/auth_context";
import { useWindowShow } from "./useWindowShow";
import { useAdmin } from "./useAdmin";
import { UserRole } from "../../core/constants/roles";
import { useGetStatesList } from "./useGetStatesList";
import axios, { AxiosError } from "axios";
import { showErrorAxios } from "../../core/utils/Messages";

// Custom hook for Super Admin Home Page operations
export const useSuperAdminHomePage = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [collapsed, setCollapsed] = useState(true);
  const { setIsWindowActive, isWindowActive } = useWindowShow();
  const [selectedPanel, setSelectedPanel] = useState<SuperAdminSelectedPanel>(
    SuperAdminSelectedPanel.TOWNS
  );
  const { user, logout } = useAuth();
  const { getAdminInfo } = useAdmin();
  const { getStates, statesList } = useGetStatesList();

  // Effect to check admin role and fetch states list
  useEffect(() => {
    const checkAdminRole = async () => {
      const admin = await getAdminInfo();
      if (admin) {
        if (admin.role !== UserRole.SUPERADMIN) {
          setError(true);
          setErrorMessage("No estas autorizado para acceder a esta página");
          setTimeout(() => {
            logout();
          }, 5000);
          return;
        }
      }
      setIsLoading(false);
    };
    checkAdminRole();

    const getStatesList = async () => {
      try {
        getStates();
        setIsLoading(false);
      } catch (error: any) {
        if (axios.isAxiosError(error)) {
          error as AxiosError;
          showErrorAxios(error);
        }
      }
    };
    getStatesList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user]);

  return {
    collapsed,
    isWindowActive,
    selectedPanel,
    setCollapsed,
    setSelectedPanel,
    setIsWindowActive,
    isLoading,
    error,
    errorMessage,
    statesList,
  };
};
