"use client";

import { useState, useEffect, useRef } from "react";
import { GET_CHECKOUT_SHIPPING_RATES, CREATE_CHECKOUT_SHIPPING_METHODS } from "@/graphql";
import {useApolloClient} from "@apollo/client/react";
import {CheckoutShippingRate, CreateCheckoutShippingMethodVariables} from "@/types/checkout/type";

interface ShippingMethodsResult {
    data: CheckoutShippingRate[];
    msg: string;
    error: boolean;
}
export function useCheckoutShippingMethod() {
    const apolloClient = useApolloClient();
    const [data, setData] = useState<CheckoutShippingRate[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string|null>(null);
    const isIntRef = useRef(true);

    const getShippingMethod = () => {
        if(!isIntRef.current) {
            setLoading(true);
        }
        return apolloClient.query({
            query: GET_CHECKOUT_SHIPPING_RATES,
            fetchPolicy: "no-cache",
            context: {
                fetchOptions: {
                    cache: 'no-store',
                },
        
            }
        }).then((res) => {
            if(isIntRef.current) {
                isIntRef.current = false;
            }
            const shippingMethods =  res.data?.collectionShippingRates || [];
            const resData: ShippingMethodsResult = {
                data: shippingMethods,
                msg: '',
                error: false
            };
            setData(resData.data);
            setLoading(false);
            console.log('GET_CHECKOUT_shippingmethod res ---- ',shippingMethods);
            // resolveCallback(resData);
            return resData;
        
        }).catch((err) => {
            if(isIntRef.current) {
                isIntRef.current = false;
            }
            console.error('GET_CHECKOUT_shippingmethod error ---- ',err);
            const resData: ShippingMethodsResult = {
                data: [],
                msg: err.message,
                error: true
            };
            setError(resData.msg);
            setLoading(false);
            // rejectCallback(resData);
            return resData;
        });
    };

    const saveShippingMethod = (params: CreateCheckoutShippingMethodVariables) => {
        return apolloClient.mutate({
            mutation: CREATE_CHECKOUT_SHIPPING_METHODS,
            variables:params,
        }).then((res) => {
            const resData = {
                data: res.data?.createCheckoutShippingMethod?.checkoutShippingMethod,
                msg: '',
                error: false
            };
            
            return resData;
        
        }).catch((err) => {
            const resData = {
                data: null,
                msg: err.message,
                error: true
            };
            
            return resData;
        });
    };

    useEffect(() => { 
        getShippingMethod();
        // getShippingMethod((resolveData) => {
        //     const methodsData = resolveData.data;
        //     setData(methodsData);
        //     setLoading(false);
        // }, (rejectData) => {
        //     setError(rejectData.msg);
        //     setLoading(false);
        // });
    }, []);


    return {
        data,
        loading,
        error,
        getShippingMethod,
        saveShippingMethod
    };
}