import { useMutation, useQuery } from "@tanstack/react-query";
import { useEffect } from "react";

import { ADDRESS_TYPES } from "../constants/app";
import { QueryKeys } from "../constants/query-keys";
import { AddressesService, ShippingCartService } from "../services/api";
import { useCartStore } from "../stores/cartStore";
import { countriesStore } from "../stores/countriesStore";

export function useShippingAddressForm() {
  //
  const { userShippingAddress, setUserShippingAddress } = useCartStore();
  //
  const { setStates, setCities, setShippingCountries } = countriesStore();

  const {
    data: userShippingAddressData,
    isLoading: isLoadingShippingAddresses,
    refetch: getShippingAddress,
  } = useQuery({
    queryKey: [QueryKeys.users.GET_SHIPPING_ADDRESSES],
    queryFn: () =>
      AddressesService.userAddressesControllerGetAllActiveUserAddresses(
        ADDRESS_TYPES.shipping.value,
      ),
    enabled: !userShippingAddress,
  });

  useEffect(() => {
    setUserShippingAddress(userShippingAddressData);
  }, [userShippingAddressData, setUserShippingAddress]);

  const getCountriesByShippingMethodId = useMutation({
    mutationKey: [QueryKeys.users.GET_COUNTRIES_BY_SHIPPING_METHOD],
    mutationFn: ({
      shippingCartId,
      shippingMethodId,
    }: {
      shippingCartId: number;
      shippingMethodId: number;
    }) =>
      ShippingCartService.shippingCartControllerGetALlowedShippingOrPickupCountries(
        shippingCartId,
        shippingMethodId,
      ),
    onSuccess: (data) => {
      setShippingCountries(data);
    },
    onError: () => {},
  });

  const addNewShippingAddress = useMutation({
    mutationKey: [QueryKeys.users.ADD_NEW_ADDRESS],
    mutationFn: AddressesService.userAddressesControllerAddNewAddress,
    onSuccess: () => {
      setStates([]);
      setCities([]);
      getShippingAddress();
    },
    onError: () => {},
  });

  return {
    shippingAddress: userShippingAddress,
    getCountriesByShippingMethodId,
    isLoadingShippingAddresses,
    getShippingAddress,
    addNewShippingAddress,
  };
}
