// Import necessary modules and hooks
import { useEffect, useState } from "react";
import { AdminSelectedPanel } from "../../core/constants/selected_panel";
import { useAuth } from "../../core/context/auth_context";
import { Town } from "../../data/datasource/api/entities/town";
import { useWindowShow } from "./useWindowShow";
import { useAdmin } from "./useAdmin";
import { UserRole } from "../../core/constants/roles";
import { useTown } from "./useTown";

// Custom hook for managing the admin home page
export const useAdminHomePage = () => {
  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<AdminSelectedPanel>(
    AdminSelectedPanel.TOWN_INFO
  );
  const { getTownById } = useTown();
  const [town, setTown] = useState<Town>();
  const { user, logout } = useAuth();
  const { getAdminInfo } = useAdmin();

  // Check admin role and fetch town info on component mount
  useEffect(() => {
    const checkAdminRole = async () => {
      const admin = await getAdminInfo();
      if (admin) {
        if (admin.role !== UserRole.ADMIN) {
          setError(true);
          setErrorMessage("No estas autorizado para acceder a esta página");
          setTimeout(() => {
            logout();
          }, 5000);
          return;
        }

        if (admin.idTown) {
          const townFetched = await getTownById(admin.idTown);
          if (townFetched) {
            setTown(townFetched);
          }
        }
      }
      setIsLoading(false);
    };
    checkAdminRole();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user]);

  // Update town information
  const updateTown = async () => {
    if (town) {
      const townFetched = await getTownById(town.idTown);
      if (townFetched) {
        setTown(townFetched);
      }
    }
  };

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