import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

import { routes } from '@/config/routes';
import { RootState } from '@/redux/store';
import { getErrorMessage } from '@/utils/helpers';
import { setCart } from '@/redux/slice/cart-slice';
import { setUser } from '@/redux/slice/user-slice';
import { useModal } from '@/components/modal/use-modal';
import { setSnackbarAlertMessage } from '@/redux/slice/snackbar-slice';

import useAuth from '@/server_api/hooks/useAuth';
import PostAPI from '@/server_api/api-functions/apipost';
import { apiEndpoints } from '@/server_api/config/api.endpoints';
import { useRouter } from 'next/navigation';
import FetchAPIData from '@/server_api/api-functions/apifetch';
import { UseMutationProps } from '@/src/constants/common';

interface UseCustomerProps {
    hostName?: string | null
    fetchWallwalletDetails?: boolean;
    fetchCustomerAddress?: boolean;
    address?: any
}
const useCustomer = ({
    hostName,
    fetchWallwalletDetails = false,
    fetchCustomerAddress = false,
}: UseCustomerProps) => {
    const dispatch = useDispatch();
    const { push } = useRouter();
    const { closeModal } = useModal();
    const { setLogOut } = useAuth();
    const queryClient = useQueryClient();

    const user = useSelector((state: RootState) => state.user);
    const guestUser = useSelector((state: RootState) => state.guestUser);
    const hasUserSession = Boolean(user && Object.keys(user).length > 0) || Boolean(guestUser && Object.keys(guestUser).length > 0);

    const [alertSuccess, setAlertSuccess] = useState<boolean>(false);

    const { data: customerAddress, isLoading: customerAddressLoading, refetch: refetchAddress } = useQuery({
        queryKey: [apiEndpoints.address.address + (guestUser ?? '')],
        queryFn: async () => {
            const retVal: any = await FetchAPIData.fetchAPIData({ apiEndpoint: apiEndpoints.address.address }, hostName);
            if (retVal && retVal.requestedData) {
                return retVal
            }
        },
        enabled: Boolean(fetchCustomerAddress && hasUserSession),
    });



    const { mutate: manageCustomerAddress, isPending: manageCustomerAddressIsLoading, error: manageCustomerAddressError } = useMutation<any, Error, UseMutationProps>({
        mutationFn: PostAPI.postAPI,
        onSuccess: async (response: any) => {
            if (response.status) {
                queryClient.invalidateQueries({ queryKey: [apiEndpoints.address.address] });
                queryClient.invalidateQueries();
                refetchAddress();
                dispatch(setSnackbarAlertMessage({
                    messages: response.message,
                    type: 'success',
                    from: 'address',
                }));
                closeModal();
            }
        },
        onError: (error: any) => {
            dispatch(setSnackbarAlertMessage({
                messages: getErrorMessage(error),
                type: 'error',
                from: 'address',
            }));
        }
    });

    const { mutate: removeAndMakeDefaultCustomerAddress, isPending: removeAndMakeDefaultCustomerAddressIsLoading, error: removeAndMakeDefaultCustomerAddressError } = useMutation<any, Error, UseMutationProps>({
        mutationFn: PostAPI.postAPI,
        onSuccess: async (response: any) => {
            if (response.status) {
                queryClient.invalidateQueries({ queryKey: [apiEndpoints.address.address] });
                queryClient.invalidateQueries();
                refetchAddress();
                dispatch(setSnackbarAlertMessage({
                    messages: response.message,
                    type: 'success',
                    from: 'address',
                }));
            }
        },
        onError: (error: any) => {
            dispatch(setSnackbarAlertMessage({
                messages: getErrorMessage(error),
                type: 'error',
                from: 'address',
            }));
        }
    });

    const { mutate: manageCustomerDetails, isPending: manageCustomerDetailsIsLoading, error: manageCustomerDetailsError, variables } = useMutation<any, Error, UseMutationProps>({
        mutationFn: PostAPI.postAPI,

        onSuccess: async (response: any, variables) => {
            if (response.status && variables?.changePassword) {
                setLogOut();
                // window.location.href = routes.login;
                dispatch(
                    setSnackbarAlertMessage({
                        messages: "Password reset successfully. Please login.",
                        type: "success",
                        from: "customer",
                    })
                );

                push(routes.auth.login);
                //window.location.href = routes.login;
                //  window.location.replace(routes.login);
                return; // do not trigger modal
            }
            // If not a password change, show modal
            setAlertSuccess(true);


            // if (response.status) {
            //     setAlertSuccess(true);
            //     // dispatch(setSnackbarAlertMessage({
            //     //     messages: response.message,
            //     //     type: 'success',
            //     //     from: 'profile',
            //     // }));
            //     if (variables?.changePassword) {
            //         setLogOut();
            //         window.location.replace(`${routes.login}`);
            //         dispatch(setUser(null));
            //         dispatch(setCart(null));
            //     }

            //  }
        },
        onError: (error: any) => {
            dispatch(setSnackbarAlertMessage({
                messages: getErrorMessage(error),
                type: 'error',
                from: 'profile',
            }));
        }
    });


    return {
        alertSuccess,
        setAlertSuccess,
        customerAddress: customerAddress?.requestedData, customerAddressLoading, refetchAddress,
        removeAndMakeDefaultCustomerAddress, removeAndMakeDefaultCustomerAddressIsLoading, removeAndMakeDefaultCustomerAddressError,
        manageCustomerAddress, manageCustomerAddressIsLoading, manageCustomerAddressError,
        manageCustomerDetails, manageCustomerDetailsIsLoading, manageCustomerDetailsError
    }
}

export default useCustomer