import { useState } from "react";
import { get, isArray } from "lodash";
import { useDispatch } from "react-redux";
import { useRouter } from "next/navigation";
import { useMutation, useQuery } from "@tanstack/react-query";

import { useModal } from "@/components/modal/use-modal";

import { routes } from "@/config/routes";
import { getErrorMessage } from "@/utils/helpers";

import { setSnackbarAlertMessage } from "@/redux/slice/snackbar-slice";

import { paymentMethods } from "@/constants/cart";
import PostAPI from "@/server_api/api-functions/apipost";
import FetchAPIData from "@/server_api/api-functions/apifetch";
import { apiEndpoints } from "@/server_api/config/api.endpoints";
import { clearDeliveryCharge, setDeliveryCharge, setPaymentMethod } from "@/redux/slice/cart-slice";
import { UseMutationProps } from "@/src/constants/common";


interface UseOrderProps {
    hostName?: string | null;
    fetchRetrieveCheckoutTabby?: boolean;
    tabbyId?: string;
    getReturnProduct?: string;
    orderId?: string;
    fetchOrderDetails?: boolean;
}
const useOrder = ({ hostName, getReturnProduct, fetchRetrieveCheckoutTabby = false, tabbyId = "", orderId = "", fetchOrderDetails = false }: UseOrderProps) => {
    const dispatch = useDispatch();
    const { push, back, refresh } = useRouter();
    const { closeModal } = useModal();

    const [checkoutIsLoadingCompletion, setCheckoutIsLoadingCompletion] = useState<boolean>(false);

    // const { mutate: checkout, isPending: checkoutIsLoading } = useMutation<any, Error, UseMutationProps>({
    //     mutationFn: PostAPI.postAPI,
    //     onSuccess: async (response: any) => {
    //         // Set a timer delay (e.g., 1500ms) before finishing completion loading and redirecting
    //         setTimeout(() => {
    //             setCheckoutIsLoadingCompletion(false);
    //             console.log("order type.....", paymentMethods);
    //             if (response.status && response.requestedData) {
    //                 const { orderId, orderType, paymentData } = response.requestedData;
    //                 console.log("response data.............", response);

    //                 // 1. Cash on Delivery or Wallet -> Success page
    //                 if (paymentMethods.cashOnDelivery === orderType) {
    //                     push(routes.orderResponse(orderId) + "?status=success");
    //                 }
    //                 // 2. Standard Credit Card / Online Payment -> Redirect to Gateway URL
    //                 else if (paymentData && paymentData.paymentRedirectionUrl) {
    //                     console.log("paymentData.paymentRedirectionUrl", paymentData.paymentRedirectionUrl);
    //                     push(paymentData.paymentRedirectionUrl);
    //                 }
    //                 else {
    //                     push(routes.orderResponse(orderId) + "?status=failed");
    //                 }
    //             } else {
    //                 dispatch(
    //                     setSnackbarAlertMessage({
    //                         messages: response?.message,
    //                         type: "error",
    //                         from: "cart",
    //                     })
    //                 );
    //             }
    //         }, 1500); // Adjust duration (in ms) as needed
    //     },
    //     onError: (error: any) => {
    //         setCheckoutIsLoadingCompletion(false);
    //         dispatch(
    //             setSnackbarAlertMessage({
    //                 messages: getErrorMessage(error),
    //                 type: "error",
    //                 from: "cart",
    //             })
    //         );
    //     },
    // });

    const { mutate: checkout, isPending: checkoutIsLoading } = useMutation<any, Error, UseMutationProps>({
        mutationFn: PostAPI.postAPI,
        onSuccess: async (response: any) => {
            setCheckoutIsLoadingCompletion(false);
            if (response.status && response.requestedData) {
                const { orderId, orderType, paymentData } = response.requestedData;

                const redirectToPaymentGateway = (url: string) => {
                    if (url) {
                        window.location.href = url;
                    } else {
                        console.warn("Payment URL not found");
                    }
                };
                if (paymentMethods.cashOnDelivery === orderType) {
                    push(routes.orderResponse(orderId) + "?status=success");
                    //push(routes.orderResponse(orderId))

                } else {
                    redirectToPaymentGateway(paymentData?.paymentRedirectionUrl);
                    //push(routes.orderResponse(orderId) + "?status=failed");
                }
            } else {
                setCheckoutIsLoadingCompletion(false);
                dispatch(
                    setSnackbarAlertMessage({
                        messages: response?.message,
                        type: "error",
                        from: "cart",
                    })
                );
            }
        },
        onError: (error: any) => {
            setCheckoutIsLoadingCompletion(false);
            if (isArray(error)) {

            } else {

                dispatch(
                    setSnackbarAlertMessage({
                        messages: getErrorMessage(error),
                        type: "error",
                        from: "cart",
                    })
                );
            }
        },
    });

    const {
        mutate: cancelOrder,
        isPending: cancelOrderIsLoading,
        error: cancelOrderError,
    } = useMutation<any, Error, UseMutationProps>({
        mutationFn: PostAPI.postAPI,
        onSuccess: async (response: any) => {
            if (response.status && response.requestedData) {
                dispatch(
                    setSnackbarAlertMessage({
                        messages: response?.message,
                        type: "success",
                        from: "order",
                    })
                );
                refresh();
                closeModal();
                //push(routes.authRequired.orders.myOrders);
            } else {
                dispatch(
                    setSnackbarAlertMessage({
                        messages: response?.message,
                        type: "error",
                        from: "order",
                    })
                );
            }
        },
        onError: (error: any) => {
            if (isArray(error)) {
                //dispatch(setErrorMessage(error));
            } else {
                dispatch(
                    setSnackbarAlertMessage({
                        messages: getErrorMessage(error),
                        type: "error",
                        from: "order",
                    })
                );
            }
        },
    });

    const {
        mutate: returnOrderProducts,
        isPending: returnOrderProductsIsLoading,
        error: returnOrderProductsError,
    } = useMutation<any, Error, UseMutationProps>({
        mutationFn: PostAPI.postAPI,
        onSuccess: async (response: any) => {
            if (response.status && response.requestedData) {
                dispatch(
                    setSnackbarAlertMessage({
                        messages: response?.message,
                        type: "success",
                        from: "order",
                    })
                );
                closeModal();
                back();
            } else {
                dispatch(
                    setSnackbarAlertMessage({
                        messages: response?.message,
                        type: "error",
                        from: "order",
                    })
                );
            }
        },
        onError: (error: any) => {
            if (isArray(error)) {
                // dispatch(setErrorMessage(error));
            } else {
                dispatch(
                    setSnackbarAlertMessage({
                        messages: getErrorMessage(error),
                        type: "error",
                        from: "order",
                    })
                );
            }
        },
    });

    const { data: orderDetails, isLoading: orderDetailsLoading } = useQuery({
        queryKey: [apiEndpoints.order.order_detail + orderId],
        queryFn: () => FetchAPIData.fetchAPIData({ apiEndpoint: apiEndpoints.order.order_detail(orderId), getReturnProduct, getattribute: "0" }, hostName),
        enabled: Boolean(fetchOrderDetails) && Boolean(orderId),
    });

    return {
        orderListApiKey: [apiEndpoints.order.order_list],
        checkout,
        checkoutIsLoading,
        checkoutIsLoadingCompletion,
        setCheckoutIsLoadingCompletion,
        cancelOrder,
        cancelOrderIsLoading,
        cancelOrderError,
        returnOrderProducts,
        returnOrderProductsIsLoading,
        returnOrderProductsError,
        orderDetails: (orderDetails as any)?.requestedData || (orderDetails as any),
        orderDetailsLoading,
    };
};

export default useOrder;
