import axios from "axios";
import { API_BASE_URL } from "../common/envVariables";
import { ERRORS, NOTIFICATION } from "../constants";
import { pushNotification } from "../utils/notification";
import { commonLogoutFunc } from "../utils/share";
import store from "../redux/store";

export const axiosInstance = axios.create({
  baseURL: API_BASE_URL,
  // crossDomain: true,
  // headers: {
  //   'Content-Type': 'application/json',
  //   // 'Access-Control-Allow-Origin': '*',
  //   // 'Access-Control-Allow-Headers': '*',
  // },
  // withCredentials: false,
  // timeout: 300000,
});

axiosInstance.interceptors.request.use(
  async function (config) {
    try {
      const token = JSON.parse(localStorage.getItem("redux"));
      if (token?.login?.token) {
        config.headers.Authorization = `Bearer ${token?.login?.token}`;
      }
      // if url is dev-ai-appointment.s3.amazonaws.com
      if (config.url?.includes("dev-ai-appointment.s3.amazonaws.com")) {
        config.headers.Authorization = null;
      }

      const state = store.getState();
      const companyId = state?.loginAsCompanyAdmin?.companyId; // Extract companyId
      if (companyId) {
        config.headers.companyId = companyId; // Attach companyId to headers
      }
      return config;
    } catch (error) {
      pushNotification(ERRORS.NETWORK_ERROR, NOTIFICATION.ERROR);
      commonLogoutFunc();
      return null;
    }
  },
  function (error) {
    if (error?.response?.data?.error && error?.response?.data?.message) {
      pushNotification(error?.response?.data?.message, NOTIFICATION.ERROR);
    }
    // Do something with request error
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  function (response) {
    if (response?.data && typeof response?.data === "object" && 'error' in response.data && response?.data?.error !== null) {
      pushNotification(response?.data?.message, NOTIFICATION.ERROR);
      return Promise.reject(response);
    }
    return response;
  },
  function (error) {
    // eslint-disable-next-line no-console
    console.log(error);
    if (!error?.response?.data) {
      pushNotification(error.message, NOTIFICATION.ERROR);
      if (error.message !== "Network Error") commonLogoutFunc();
    } else if (
      error?.response?.data?.error &&
      error?.response?.data?.error[0]?.message
    ) {
      pushNotification(
        error?.response?.data?.error[0]?.message,
        NOTIFICATION.ERROR
      );
    } else if (error?.response?.data?.message) {
      pushNotification(error?.response?.data?.message, NOTIFICATION.ERROR);
    }
    // else if (
    //   error?.response?.status === 440 ||
    //   error?.response?.status === 401 ||
    //   error?.response?.status === 403
    // ) {
    //   pushNotification(ERRORS.SESSION_EXPIRED_ERROR, NOTIFICATION.ERROR);
    //   // commonLogoutFunc();
    // }
    else if (error?.response?.status === 440 || error?.error?.status === 401) {
      pushNotification(ERRORS.SESSION_EXPIRED_ERROR, NOTIFICATION.ERROR);
      // commonLogoutFunc();
    }
    // else if (error?.response?.data?.error && error?.response?.data?.message) {
    //   pushNotification(error?.response?.data?.message, NOTIFICATION.ERROR);
    // }
    return Promise.reject(error);
  }
);

export const fileDownloadAxios = axios.create({
  baseURL: API_BASE_URL,
  responseType: "blob",
  crossDomain: true,
  headers: {
    "Content-Type": "application/json",
  },
  withCredentials: true,
  timeout: 300000,
});

fileDownloadAxios.interceptors.request.use(
  async function (config) {
    try {
      const token = JSON.parse(localStorage.getItem("redux"));
      if (token?.data?.data) {
        config.headers.Authorization = `${token?.data?.data}`;
      }

      // if url is dev-ai-appointment.s3.amazonaws.com
      if (config.url?.includes("dev-ai-appointment.s3.amazonaws.com")) {
        config.headers.Authorization = null;
      }

      const state = store.getState();
      const companyId = state?.loginAsCompanyAdmin?.companyId; // Extract companyId
      if (companyId) {
        config.headers.companyId = companyId; // Attach companyId to headers
      }
      return config;
    } catch (error) {
      pushNotification(ERRORS.NETWORK_ERROR, NOTIFICATION.ERROR);
      commonLogoutFunc();
      return null;
    }
  },
  function (error) {
    if (error?.response?.data?.error && error?.response?.data?.message) {
      pushNotification(error?.response?.data?.message, NOTIFICATION.ERROR);
    }
    return Promise.reject(error);
  }
);

fileDownloadAxios.interceptors.response.use(
  async function (response) {
    // Handle error response (when server responds with JSON instead of a file)
    if (
      response?.headers["content-type"]?.includes("application/json") &&
      response?.data
    ) {
      try {
        const errorData = await response.data.text(); // Convert blob to text
        const parsedError = JSON.parse(errorData);

        if (parsedError?.error) {
          pushNotification(
            parsedError?.message || "Download failed",
            NOTIFICATION.ERROR
          );
          return Promise.reject(parsedError);
        }
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error("Error parsing error response", err);
      }
    }

    return response;
  },
  function (error) {
    // eslint-disable-next-line no-console
    console.error(error);

    if (!error?.response?.data) {
      pushNotification(error.message, NOTIFICATION.ERROR);
      if (error.message !== "Network Error") commonLogoutFunc();
    } else {
      // Handle error message from API
      const contentType = error?.response?.headers?.["content-type"];

      if (contentType?.includes("application/json")) {
        error.response.data.text().then((text) => {
          try {
            const parsedError = JSON.parse(text);
            pushNotification(
              parsedError.message || "Something went wrong",
              NOTIFICATION.ERROR
            );
          } catch (err) {
            pushNotification("Unknown error occurred", NOTIFICATION.ERROR);
          }
        });
      } else {
        pushNotification(
          error?.response?.data?.message || "Download failed",
          NOTIFICATION.ERROR
        );
      }
    }

    // Handle session expiration
    if (error?.response?.status === 440 || error?.response?.status === 401) {
      pushNotification(ERRORS.SESSION_EXPIRED_ERROR, NOTIFICATION.ERROR);
      commonLogoutFunc();
    }

    return Promise.reject(error);
  }
);
