"use client";

import { useEffect, useState, useRef } from "react";
import { GET_CHECKOUT_PAYMENT_METHODS, CREATE_CHECKOUT_PAYMENT_METHODS } from "@/graphql";
import {useApolloClient} from "@apollo/client/react";
import {CheckoutPaymentMethod, CreateCheckoutPaymentMethodVariables} from "@/types/checkout/type";

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

    const getPaymentMethod = () => {
        if(!isIntRef.current) {
            setLoading(true);
        }
        return apolloClient.query({
            query: GET_CHECKOUT_PAYMENT_METHODS,
            fetchPolicy: "no-cache",
            context: {
                fetchOptions: {
                    cache: 'no-store',
                },
        
            }
        }).then((res) => {
            if(isIntRef.current) {
                isIntRef.current = false;
            }
            const paymentMethods =  res.data?.collectionPaymentMethods || [];
            const resData: PaymentMethodsResult = {
                data: paymentMethods,
                msg: '',
                error: false
            };

            setData(resData.data);
            setLoading(false);
            
            console.log('GET_CHECKOUT_paymentmethod res ---- ',paymentMethods);
            
            return resData;
        
        }).catch((err) => {
            if(isIntRef.current) {
                isIntRef.current = false;
            }
            console.error('GET_CHECKOUT_paymentmethod error ---- ',err);
            const resData: PaymentMethodsResult = {
                data: [],
                msg: err.message,
                error: true
            };
            setError(resData.msg);
            setLoading(false);
            
            return resData;
        });
    };

    const savePaymentMethod = (params: CreateCheckoutPaymentMethodVariables) => {
        return apolloClient.mutate({
            mutation: CREATE_CHECKOUT_PAYMENT_METHODS,
            variables:params,
        }).then((res) => {
            const resData = {
                data: res.data?.createCheckoutPaymentMethod?.checkoutPaymentMethod,
                msg: '',
                error: false
            };
            
            return resData;
        
        }).catch((err) => {
            const resData = {
                data: null,
                msg: err.message,
                error: true
            };
            
            return resData;
        });
    };

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

    return {
        data,
        loading,
        error,
        getPaymentMethod,
        savePaymentMethod
    };
}