/* eslint-disable @typescript-eslint/no-explicit-any */
import axios from "axios";

import { clearData } from "../lib/keyStorage";

const urlRegex = new RegExp("^https?:\\/\\/\\S+$");
const isUrl = (str: string) => urlRegex.test(str);

class Api {
  url: string;

  constructor() {
    this.url = process.env.NEXT_PUBLIC_API_BASE_URL || "";

    axios.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response && error.response.status === 401) {
          if (!error?.response?.request?.responseURL.includes("/dashboard")) {
            clearData();
            // window.location.reload();
          }
        }
        return Promise.reject(error);
      }
    );
  }

  private getApiUrl(path: string) {
    return isUrl(path) ? path : this.url + path;
  }

  async get(path: string, auth: boolean = false, headers: any = {}, params: any = {}, responseType: any = 'json') {
    try {
      const response = await axios.get(this.getApiUrl(path), {
        timeout: 20000,
        headers: {
          mode: "cors",
          referrerPolicy: "origin",
          "Content-Type": "application/json",
          Accept: "application/json",
          "Access-Control-Allow-Origin": "*",
          ...(auth
            ? { Authorization: `Bearer ${localStorage.getItem("AUTH_TOKEN")}` }
            : {}),
          ...headers,
        },
        params,
        responseType
      });
      return [true, response.data, response.status];
    } catch (error: any) {
      console.error("GET request error:", error);
      return [false, null, error?.response?.status || 500];
    }
  }
  

  async post(
    path: string,
    data: object = {},
    auth: boolean = false,
    headers: object = {}
  ) {
    try {
      const response = await axios.post(this.getApiUrl(path), data, {
        headers: {
          mode: "cors",
          referrerPolicy: "origin",
          "Content-Type": "application/json",
          Accept: "application/json",
          "Access-Control-Allow-Origin": "*",
          ...(auth
            ? { Authorization: `Bearer ${localStorage.getItem("AUTH_TOKEN")}` }
            : {}),
          "X-Requested-With": "XMLHttpRequest",
          ...headers,
        },
      });
      return [true, response.data, response.status];
    } catch (error: any) {
      console.error("POST request error:", error);
      return [false, error?.response?.data, error?.response?.status || 500];
    }
  }

  async delete(
    path: string,
    data: object = {},
    auth: boolean = false,
    headers: object = {}
  ) {
    try {
      const response = await axios.delete(this.getApiUrl(path), {
        timeout: 20000,
        headers: {
          mode: "cors",
          referrerPolicy: "origin",
          "Content-Type": "application/json",
          Accept: "application/json",
          "Access-Control-Allow-Origin": "*",
          ...(auth
            ? { Authorization: `Bearer ${localStorage.getItem("AUTH_TOKEN")}` }
            : {}),
          "X-Requested-With": "XMLHttpRequest",
          ...headers,
        },
        ...data,
      });
      return [true, response.data, response.status];
    } catch (error: any) {
      console.error("DELETE request error:", error);
      return [false, null, error?.response?.status || 500];
    }
  }

  async put(
    path: string,
    data: object = {},
    auth: boolean = false,
    headers: object = {}
  ) {
    try {
      const isFormData = data instanceof FormData;
      const response = await axios.put(this.getApiUrl(path), data, {
        timeout: 20000,
        headers: {
          mode: "cors",
          referrerPolicy: "origin",
          "Content-Type": isFormData ? "multipart/form-data" : "application/json",
          Accept: "application/json",
          "Access-Control-Allow-Origin": "*",
          ...(auth
            ? { Authorization: `Bearer ${localStorage.getItem("AUTH_TOKEN")}` }
            : {}),
          "X-Requested-With": "XMLHttpRequest",
          ...headers,
        },
      });
      return [true, response.data, response.status];
    } catch (error: any) {
      console.error("PUT request error:", error);
      return [false, error?.response?.data, error?.response?.status || 500];
    }
  }

  async patch(
    path: string,
    data: object = {},
    auth: boolean = false,
    headers: object = {}
  ) {
    try {
      const response = await axios.patch(this.getApiUrl(path), data, {
        headers: {
          Accept: "application/json",
          mode: "cors",
          referrerPolicy: "origin",
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          ...(auth
            ? { Authorization: `Bearer ${localStorage.getItem("AUTH_TOKEN")}` }
            : {}),
          ...headers,
        },
      });
      return [true, response.data, response.status];
    } catch (error: any) {
      console.error("PATCH request error:", error);
      return [false, null, error?.response?.status || 500];
    }
  }

  async postFormData(
    path: string,
    formData: FormData,
    auth: boolean = false,
    headers: object = {}
  ) {
    try {
      const response = await axios.post(this.getApiUrl(path), formData, {
        headers: {
          mode: "cors",
          referrerPolicy: "origin",
          "Content-Type": "multipart/form-data",
          Accept: "application/json",
          "Access-Control-Allow-Origin": "*",
          ...(auth
            ? { Authorization: `Bearer ${localStorage.getItem("AUTH_TOKEN")}` }
            : {}),
          "X-Requested-With": "XMLHttpRequest",
          ...headers,
        },
      });
      return [true, response.data, response.status];
    } catch (error: any) {
      console.error("FormData submission error:", error);
      return [false, null, error?.response?.status || 500];
    }
  }
}

export const api = new Api();
