import { decryptData } from "@/utils/cryptoUtils";
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import Router from "next/router";
import { toast } from "react-toastify";
import Swal from "sweetalert2";

interface IResponse {
  status: string;
  body: any;
}

class ToastAxios {
  public axiosCreated: any;

  constructor(baseURL?: string) {
    this.axiosCreated = axios.create({ baseURL });
  }

  async get(
    url: string,
    // options?: AxiosRequestConfig
    options?: any,
  ): Promise<IResponse> {
    const userData = this.getUserData();

    let sigla = "";
    if (!url.includes("&sigla=")) {
      sigla = `&sigla=${userData.sigla == undefined ? "undefined" : userData.sigla}`;
    }

    return this.axiosCreated
      .get(`${url}${sigla}`, options)
      .then((response: AxiosResponse) => {
        if (typeof response.data == "string") {
          throw new AxiosError(
            "Erro inesperado, contate o suporte!  " + response.data,
          );
        }
        if (!response.data.status) {
          throw new AxiosError(response.data.body);
        }
        return response.data;
      })
      .catch((error: AxiosError) => {
        // Precisa de erro
        if (options && options["noToast"]) {
          throw error.message;
          //   throw error.message;
          //   return console.error(error.message);
        }
        toast.error(error.message);
        throw error.stack;
      });
  }

  async post(
    url: string,
    data: any,
    // options?: AxiosRequestConfig
    options?: any,
  ): Promise<any> {
    // Validação para qualquer chave que contenha "telefone"
    for (const key in data) {
      if (key.toLowerCase().includes("telefone")) {
        const telefone = data[key]?.replace(/\D/g, ""); // Remove caracteres não numéricos

        if (telefone?.length != 0 && telefone?.length < 10) {
          toast.error(
            `O campo telefone deve conter ao menos 10 dígitos no formato brasileiro.`,
          );
          return Promise.reject(
            `O campo telefone deve conter ao menos 10 dígitos no formato brasileiro.`,
          );
        }
      }
    }
    const userData = this.getUserData();
    // Precisa de loading
    let sigla = "";
    if (!url.includes("&sigla=")) {
      sigla = `&sigla=${userData.sigla == undefined ? "undefined" : userData.sigla}`;
    }

    if (options && options["noToast"]) {
      const { noToast, ...newOptions } = options;
      const promise = new Promise((resolve, reject) => {
        return this.axiosCreated
          .post(`${url}${sigla}`, data, newOptions)
          .then((response: AxiosResponse) => {
            if (typeof response.data == "string") {
              reject("Erro inesperado, contate o suporte!  " + response.data);
            }
            if (!response.data.status) {
              reject(response.data.body);
            }
            if (response?.data?.msg) {
              Swal.fire({
                title: response?.data?.title,
                icon: response?.data?.status == 1 ? "success" : "warning",
                html: response?.data?.msg,
                confirmButtonText: "OK",
                confirmButtonColor: "#4CAF50",
                cancelButtonText: "Cancelar",
                showCancelButton: true,
                cancelButtonColor: "#d33",
              }).then((result) => {
                if (result.isConfirmed) {
                  Router.push(
                    `/CXESCRM002?funil=${response?.data?.body?.id_funil}`,
                  );
                }
              });
            }
            resolve(response.data);
          })
          .catch((err: any) => err);
      });
      return promise;
    }
    const resolve = new Promise((resolve, reject) => {
      this.axiosCreated
        .post(`${url}${sigla}`, data, options)
        .then((response: any) => {
          if (typeof response.data == "string") {
            throw new AxiosError(
              "Erro inesperado, contate o suporte!  " + response.data,
            );
          }
          // if (response.data.status.includes("sucesso")) {
          if (response.data.status) {
            resolve(response.data);
          } else {
            reject(response.data.body);
          }
        })
        .catch((error: AxiosError) => {
          reject(error.message);
          if (error.message.includes("500")) {
            throw error.response?.data;
          } else {
            throw error.stack;
          }
        });
    });

    return toast.promise(resolve, {
      pending: {
        render(data: any) {
          return "Aguarde";
        },
      },
      success: {
        render(data: any) {
          if (data.data.body.token) {
            return "Sucesso!";
          }
          const response = data.data.body;
          if (response.msg) {
            Swal.fire({
              title: response.title,
              icon: response.status == 1 ? "success" : "warning",
              html: response?.msg,
              confirmButtonText: "OK",
              confirmButtonColor: "#4CAF50",
            });
            return response.title;
          }
          // if (response.status == 1) {
          //   Swal.fire({
          //     title: response.title,
          //     icon: "success",
          //     html: response?.msg,
          //     confirmButtonText: "OK",
          //     confirmButtonColor: "#4CAF50",
          //   });
          //   return response.title;
          // } else if (response.status == 0) {
          //   Swal.fire({
          //     title: response.title,
          //     icon: "warning",
          //     html: response?.msg,
          //     confirmButtonText: "OK",
          //     confirmButtonColor: "#4CAF50",
          //   });

          //   return response.title;
          // }
          return data.data.body;
        },
        theme: "light",
      },
      // error: {
      //   render(data: any) {
      //     // return data.data.body;
      //     return data.data;
      //   },
      // },
      error: {
        render(data: any) {
          // return data.data.body;
          // return data.data;
          return <div dangerouslySetInnerHTML={{ __html: data.data }}></div>;
        },
      },
    });
  }

  async delete(url: string, options?: AxiosRequestConfig): Promise<any> {
    const userData = this.getUserData();

    const resolve = new Promise((resolve, reject) => {
      let sigla = "";
      if (!url.includes("&sigla=")) {
        sigla = `&sigla=${userData.sigla == undefined ? "undefined" : userData.sigla}`;
      }
      this.axiosCreated
        .post(`${url}${sigla}`, options)
        .then((response: any) => {
          // resolve(response.data.status);
          if (response.data.status) {
            resolve("Operação realizada com sucesso!");
          } else {
            reject(response.data.body);
          }
        })
        .catch((err: any) => {
          reject(err.data.body);
        });
    });

    return toast
      .promise(resolve, {
        pending: "Aguarde",
        success: "Sucesso",
        error: "Erro",
      })
      .then((response) => response);
    // Precisa de loading
    // return this.axiosCreated
    //     .delete(url, options)
    //     .then((response: AxiosResponse) => {
    //         // Pode ser success ou error
    //         if (response.data.status.includes("sucesso")) {
    //             this.toastSuccess("Operação realizada com sucesso!");
    //         } else {
    //             this.toastError(response.data.body);
    //         }
    //         return response.data;
    //     });
  }

  getUserData() {
    let userData: any = {};
    if (typeof window !== "undefined") {
      // ... código que acessa a localStorage
      let sessionJson = decryptData(
        window.localStorage.getItem("@userSession"),
      );
      if (!sessionJson) {
        sessionJson = "{}";
      }
      userData = sessionJson;
      // //(userData)
    }
    return userData;
  }
}

const isLocalhost =
  typeof window !== "undefined" && window.location.href.includes("localhost");
const isDev =
  typeof window !== "undefined" && window.location.href.includes("dev-linksun");
const isHom =
  typeof window !== "undefined" &&
  window.location.href.includes("homologacao-linksun");

const getBackendUrl = () => {
  switch (true) {
    case isLocalhost:
      return "http://localhost:8000/NovoLinksun/back-end/index.php";
    case isDev:
      return "https://linksun.inf.br/back-end-others/index.php";
    case isHom:
      return "https://linksun.inf.br/back-end-hom/index.php";
    default:
      return "https://linksun.inf.br/back-end/index.php";
  }
};

const LinksunBackend = new ToastAxios(getBackendUrl());

export { LinksunBackend };
