import {DELETE, GET, PATCH, POST, PUT} from "@/services/axios/resources/resourcesAPI";
import {useState} from "react";
import Loading from "@/components/ui/Loading/loading";
import toast from "react-hot-toast";


export default function Actions({
                                    actions = [],
                                    requiredFieldValues = {},
                                    setRequiredFieldErrors,
                                    setOutputFieldsResponse = []
                                }) {

    const [loading, setLoading] = useState(false);
    const Tag = actions?.type || "span";

    async function handleAction() {
        if (loading) return;

        if (typeof window === "undefined") return;
        const token = localStorage.getItem("accessToken");

        if (!token) {
            toast.error("ابتدا وارد شوید سپس دوباره تلاش کنید!..");
            return;
        }

        if (!actions?.apiUrl || !actions?.method) {
            return null
        }

        const payload = {
            fields: requiredFieldValues
        }
        const method = actions.method.toUpperCase();

        setLoading(true)
        try {
            let response;

            switch (method) {
                case "POST":
                    response = await POST(actions.apiUrl, payload);
                    break;
                case "PUT":
                    response = await PUT(actions.apiUrl, payload);
                    break;
                case "DELETE":
                    response = await DELETE(actions.apiUrl, payload);
                    break;
                case "PATCH":
                    response = await PATCH(actions.apiUrl, payload);
                    break;
                default:
                    console.error(`❌ Unsupported method: ${method}`);
                    return;
            }

            setOutputFieldsResponse(response.outputs)
            setRequiredFieldErrors({})

        } catch (error) {
            console.error("❌ Request failed:", error);
            setRequiredFieldErrors(error.response.data.errors);
        } finally {
            setLoading(false);
        }
    }

    return (

        <Tag className={`${actions?.class || ""} `} onClick={handleAction}>
            {loading ?
                <Loading/>
                :
                actions?.label || ""
            }

        </Tag>
    );
}
