import React, { useCallback, useState } from 'react';
import axios from 'axios';
import { useMsal } from '@azure/msal-react';
import { useUser } from "../context/UserContext.js";
import RoleChangedPopup from "../components/RoleChangedPopup.js";

const API_BASE_URL = process.env.REACT_APP_API_BASE_URL;
const useApiService = () => {
  const { instance, accounts } = useMsal();
  const { logout, user, openRoleChangedPopup, setOpenRoleChangedPopup } = useUser();
  const account = accounts[0];
  const [message, setMessage] = useState("");

  // Remove duplicate useTokenExpiryMonitor usage - it's already handled in App.js

  const handleRoleChanged = useCallback((errorMessage) => {
    console.log(errorMessage, "error message");
    localStorage.setItem("ErrorMessage", errorMessage);
    setMessage(errorMessage);
    setOpenRoleChangedPopup(true);
  }, [setOpenRoleChangedPopup]);

  const handleLogout = useCallback(() => {
    setOpenRoleChangedPopup(false);
    logout();
    instance.logoutRedirect();
  }, [logout, instance, setOpenRoleChangedPopup]);

  const createApiClient = async () => {
    const response = await instance.acquireTokenSilent({
      scopes: ["User.Read"],
      account,
    });

    return axios.create({
      baseURL: API_BASE_URL,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${response.accessToken}`,
        'RoleId': user?.user_role_id || '',
      },
    });
  };

  const handleApiError = (error) => {
    const { status, data } = error?.response || {};
    const errorMsg = data?.Message;

    if (!data?.IsSuccess && errorMsg === "You are not Authorized") {
      logout();
      instance.logoutRedirect();
      return true;
    }

    const errorConditions = [
      { status: 498, message: "Role Changed. Please Re-Login" },
      { status: 499, message: "User has been deleted. Please contact the administrator." },
      { status: 497, message: "User Status changed to Inactive. Please contact the administrator." },
    ];

    for (const { status: errorStatus, message } of errorConditions) {
      if (status === errorStatus && errorMsg?.includes(message)) {
        handleRoleChanged(message);
        return true;
      }
    }

    return false;
  };

  const postApi = async (endpoint, data, requireData = false) => {
    try {
      const apiClient = await createApiClient();
      const res = await apiClient.post(endpoint, data);

      if (!res?.data?.IsSuccess && res?.data?.Message === "Not a valid token.") {
        logout();
        instance.logoutRedirect();
      }

      return requireData ? res.data : res.data?.Data;
    } catch (error) {
      console.error('Error fetching data', error);
      if (handleApiError(error)) return;
    }
  };

  const getApi = async (endpoint) => {
    try {
      const apiClient = await createApiClient();
      const res = await apiClient.get(endpoint);

      if (!res?.data?.IsSuccess && res?.data?.Message === "Not a valid token.") {
        logout();
        instance.logoutRedirect();
      }

      return res.data?.Data;
    } catch (error) {
      console.error('Error getting data', error);
      if (handleApiError(error)) return;
    }
  };

  const RoleChangedPopupElement = (
    <RoleChangedPopup open={openRoleChangedPopup} onLogout={handleLogout} message={message} />
  );

  return { postApi, getApi, RoleChangedPopupElement };
};

export default useApiService;
