/* eslint-disable no-empty */

import axios from "axios";
import { CONST } from "./Const";
import { toast } from "react-toastify";







export function authHeader() {
    const user = JSON.parse(localStorage.getItem(`token`) || 'null');
    if (user ) {
        return { 'Authorization': 'Bearer ' + user };
    } else {
        return {};
    }
}

export const apiCall = async (method, path, payload) => {
    try {
        const response = await axios({
            method,
            url: CONST.BACKEND_URL + path,
            data: payload,
            headers: {
                'Content-Type': 'application/json',
                ...authHeader(),
            },
        });

        return response.data;
    } catch (error) {
        if (Number(error?.response?.data?.code) === 3 || Number(error?.response?.status) === 401) {
            localStorage.clear();
            window.location.href = '/dashboard';
        } else if (error.response) {
            throw error.response;
        } else if (error.request) {
            throw new Error('No response received from the server');
        } else {
            console.error(error, "Error occurred during request setup");
            throw new Error(error.message);
        }
    }
};
export const apiCallCasino = async (method, path, payload) => {
    try {
        const response = await axios({
            method,
            url: CONST.CASINO_URL + path,
            data: payload,
            headers: {
                'Content-Type': 'application/json',
                ...authHeader(),
            },
        });

        return response.data;
    } catch (error) {
        if (Number(error?.response?.data?.code) === 3 || Number(error?.response?.status) === 401) {
            localStorage.clear();
            window.location.href = '/dahboard';
        } else if (error.response) {
            throw error.response;
        } else if (error.request) {
            throw new Error('No response received from the server');
        } else {
            console.error(error, "Error occurred during request setup");
            throw new Error(error.message);
        }
    }
};


export const httpGet = async (url, params) => {
    try {
        let headers = {
            'Content-Type': 'application/json',
            // 'Access-Control-Allow-Origin': '*',
            "Authorization": authHeader().Authorization
        };

        const result = await axios({
            method: "GET",
            url: CONST.BACKEND_URL + url,
            data: { ...params },
            headers: headers,
        });

        invalidToken(result);

        return result;
    } catch (err) {
        console.error(err);
        if (err.request.status) {
            invalidHeadres(err.request.status);
        }
    }
};

export const httpGetWithoutToken = async (url, params) => {
    try {
        let headers = {
            'Content-Type': 'application/json',
            // 'Access-Control-Allow-Origin': '*',
        };

        const result = await axios({
            method: "GET",
            url: CONST.BACKEND_URL + url,
            data: { ...params },
            headers: headers,
        });

        invalidToken(result);

        return result;
    } catch (err) {
        console.error(err);
        if (err.request.status) {
            invalidHeadres(err.request.status);
        }
    }
};

export const httpPost = async (url, params, isNotify) => {
    try {
        let headers = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            "Authorization": authHeader().Authorization
        };
        const result = await axios({
            method: "POST",
            url: CONST.BACKEND_URL + url,
            data: { ...params },
            headers: headers,
        });


        // await invalidToken(result);

        if (result.data) {
            if (result.data.error && isNotify) {
                // error(result.message)
                //alert(result.data.message)
            }
            else if (isNotify && !result.data.error) {
                // toast.success(result.data.message)
                // alert(result.data.message)
            }
            return result.data
        } else {
            return false
        }
    } catch (err) {
        console.error(err);
        const toastId = toast.error(err?.response?.data?.message);
        setTimeout(() => toast.dismiss(toastId), 1000);
        if (err.request.status) {
            invalidHeadres(err.request.status);
        }
    }
};


export const httpPostWithoutToken = async (url, params, isNotify) => {
    try {
        let headers = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        };
        const result = await axios({
            method: "POST",
            url: CONST.BACKEND_URL + url,
            data: { ...params },
            headers: headers,
        });


        // await invalidToken(result);

        if (result.data) {
            if (result.data.error && isNotify) {
                // error(result.message)
                //alert(result.data.message)
            }
            else if (isNotify && !result.data.error) {
                // toast.success(result.data.message)
                // alert(result.data.message)
            }
            return result.data
        } else {
            return false
        }
    } catch (err) {
        console.error(err);
        const toastId = toast.error(err?.response?.data?.message);
        setTimeout(() => toast.dismiss(toastId), 1000);
        if (err.request.status) {
            invalidHeadres(err.request.status);
        }
    }
};

export const httpPostFormData = async (url, data, isNotify) => {
    try {
        const result = await axios({
            method: "POST",
            url: CONST.BACKEND_URL + url,
            data: data,
            headers: {
                'Content-Type': 'multipart/form-data',
                "Authorization": authHeader().Authorization
            },
        });

        if (result.data) {
            if (result.data.error && isNotify) {
                // Optionally handle errors here
                // alert(result.data.message)
            } else if (isNotify && !result.data.error) {

                console.error("error in form data")
            }
            return result.data;
        } else {
            return false;
        }
    } catch (err) {
        console.error(err);
        toast.error(err?.response?.data?.message); // Display error toast
        if (err.request.status) {
            invalidHeadres(err.request.status); // Handle specific errors (e.g., token expiration)
        }
    }
};


export const httpPatch = async (url, params, isNotify) => {
    try {
        let headers = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            "Authorization": authHeader().Authorization
        };
        const result = await axios({
            method: "PATCH",
            url: CONST.BACKEND_URL + url,
            data: { ...params },
            headers: headers,
        });

        // invalidToken(result);
        if (result.data) {
            if (result.data.error && isNotify) {
                // error(result.message)
                //alert(result.data.message)
            }
            else if (isNotify && !result.data.error) {
                // success(result.message)
                //alert(result.data.message)
            }
        } else {
            return false
        }

        return result.data
    } catch (err) {
        console.error(err);
        if (err.request.status) {
            invalidHeadres(err.request.status);
            // toast.error(err.response.data.message);
        }
    }
};


export const httpPostBet = async (url, params) => {

    let header = new Headers({
        'Content-Type': 'application/json',
        "Authorization": authHeader().Authorization
    });
    const requestOptions = {
        method: "POST",
        headers: header,
        body: JSON.stringify(params)
    }
    try {
        const response = await fetch(CONST.BACKEND_URL + url, requestOptions);
        const responseData = await response.json();
        return responseData;
    } catch (error) {
        console.error("Error in httpPostBet:", error);
        throw error;
    }

};


const invalidToken = async (result) => {
    if (result.data.code === 3) {
        localStorage.clear();
        window.location.href = '/dashboard';
    }
};

const invalidHeadres = async (status = "") => {
    if (status === 401) {
        localStorage.clear();
        window.location.href = '/dashboard';
    }
};