import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { apiGet } from "../../../../lib/api/methods";
import { PaginationController } from "../../../useAppPagination";
import { ADMIN_CONTACTS } from "./endpoints";

export type AdminContactRequest = {
  uuid: string;
  firstName: string;
  lastName: string;
  email: string;
  dialCode: string;
  phoneNumber: string;
  query: string;
  createdAt: string;
  name?: string;
  phone?: string;
};

type AdminContactRequestsResponse = AdminContactRequest[];

export default function useContactRequestsFetch(
  pagination: PaginationController,
) {
  const { data, isPending, isError, error } = useQuery({
    queryKey: [
      "admin-contact-requests",
      pagination.params.page,
      pagination.params.limit,
      pagination.params.searchQuery,
      pagination.params.sortBy,
      pagination.params.sortDirection,
    ],
    queryFn: async () => {
      const queryParams = {
        limit: pagination.params.limit,
        page: pagination.params.page,
        search: pagination.params.searchQuery,
        sortBy: pagination.params.sortBy,
        sortOrder: pagination?.params?.sortDirection?.toUpperCase(),
      };

      const res = await apiGet<AdminContactRequestsResponse>(
        ADMIN_CONTACTS.GET_CONTACT_REQUESTS,
        queryParams,
      );

      return {
        contacts: res.data.map((contact) => ({
          ...contact,
          name: `${contact.firstName} ${contact.lastName}`.trim(),
          phone: `${contact.dialCode} ${contact.phoneNumber}`.trim(),
        })),
        pagination: res.meta,
      };
    },
    staleTime: 2 * 60 * 1000,
    placeholderData: keepPreviousData,
    retry: false,
  });

  return {
    data,
    loading: isPending,
    error,
    isError,
  };
}
