import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuthToken } from "../hooks/use-root-data";
import { Address } from "../../src/api/types";
import { createUserManagementApi } from "~/utils/api-client-factory";

export function useServiceGetAddresses() {
  const token = useAuthToken();
  const response = useQuery({
    enabled: !!token,
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["getAddressesService"],
    queryFn: async () => {
      const userApi = createUserManagementApi(token);
      return await userApi.apiUserV1AddressList();
    },
  });

  return { ...response };
}

export function useServiceGetAddressById(addressId: string) {
  const token = useAuthToken();
  const response = useQuery({
    enabled: !!token && !!addressId,
    retry: 1,
    retryDelay: 3000,
    refetchOnWindowFocus: false,
    queryKey: ["getAddressByIdService", addressId],
    queryFn: async () => {
      const userApi = createUserManagementApi(token);
      return await userApi.apiUserV1AddressRead({ id: addressId });
    },
  });

  return { ...response };
}

export function useServiceCreateAddress() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (addressData: {
      title: string;
      receiver_name: string;
      phone_number: string;
      main_address: string;
      postal_code: string;
      entry_reference: string;
      details: string;
      latitude: number;
      longitude: number;
      is_default: boolean;
    }) => {
      // Map the fields to match the Address interface
      const apiAddressData = {
        title: addressData.title,
        receiverName: addressData.receiver_name,
        phoneNumber: addressData.phone_number,
        mainAddress: addressData.main_address,
        postalCode: addressData.postal_code,
        entryReference: addressData.entry_reference,
        details: addressData.details,
        latitude: addressData.latitude,
        longitude: addressData.longitude,
        isDefault: addressData.is_default,
      };

      const userApi = createUserManagementApi(token);
      return await userApi.apiUserV1AddressCreateCreate({
        data: apiAddressData,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getAddressesService"] });
    },
  });
}

export function useServiceDeleteAddress(
  addressId: string,
  title: string,
  toast: (toast: {
    title: string;
    description?: string;
    variant?: "default" | "destructive";
  }) => void
) {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async () => {
      const userApi = createUserManagementApi(token);
      try {
        await userApi.apiUserV1AddressDeleteDelete({ id: addressId });
        toast({
          title: `آدرس "${title}" با موفقیت حذف شد.`,
        });
        return null;
      } catch (error) {
        toast({
          title: "خطا در حذف آدرس",
          description:
            "متاسفانه مشکلی در حذف آدرس پیش آمده است. لطفا دوباره تلاش کنید.",
          variant: "destructive",
        });
        throw error;
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getAddressesService"] });
    },
  });
}

export function useServiceUpdateAddress(
  addressId: string,
  addressData: Address
) {
  const token = useAuthToken();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async () => {
      // Map the fields to match the Address interface
      const apiAddressData = {
        title: addressData.title,
        receiverName: addressData.receiverName,
        phoneNumber: addressData.phoneNumber,
        mainAddress: addressData.mainAddress,
        postalCode: addressData.postalCode,
        entryReference: addressData.entryReference,
        details: addressData.details,
        latitude: addressData.latitude,
        longitude: addressData.longitude,
        isDefault: addressData.isDefault,
      };

      const userApi = createUserManagementApi(token);
      return await userApi.apiUserV1AddressUpdatePartialUpdate({
        id: addressId,
        data: apiAddressData,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getAddressesService"] });
    },
  });
}

export function useServiceSetDefaultAddress() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (addressId: string) => {
      const userApi = createUserManagementApi(token);
      // The API requires setting isDefault to true in an Address object
      return await userApi.apiUserV1AddressSetDefaultPartialUpdate({
        id: addressId,
        data: { isDefault: true } as Address,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["getAddressesService"] });
    },
  });
}
