import { fetchAttachment } from "@/record-management/services/api/attachmentService";
import {
  getIncoming,
  getIncomingParent,
  getIncomingV2,
} from "@/record-management/services/api/incomingRecordService";
import { MeDto } from "@/shared/dto/user/meDto";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useUserDetail } from "./useUserDetail";
import { useAuthUser } from "@/shared/hooks/useAuthUser";

export interface UseInternalIncomingRecordsParams {
  pageIndex?: number;
  pageSize?: number;
  status?: string;
  filterType?: string; // "Department" | "Subject" | "Date" | "Reference Number"
  searchQuery?: string;
  order?: string;
  letterNumber?: string;
  referenceNumber?: string;
  subject?: string;
  recordTypeKey?: string;
  fromCreatedAt?: string;
  toCreatedAt?: string;
  fromSubmittedAt?: string;
  toSubmittedAt?: string;
  fromDispatchedDate?: string;
  toDispatchedDate?: string;
  receiverPosition?: string;
  receiverEmployee?: string;
  sendingPosition?: string;
  sendingEmployee?: string;
  receiverUnit?: string;
  dispatchedBy?: string;
  from?: string; // Sender information filter
  fetchParent?: boolean;
  isUrgent?: boolean;
  isRO?: boolean;
}

export const useInternalIncomingRecords = ({
  pageIndex,
  pageSize,
  status,
  filterType,
  searchQuery,
  fetchParent,
  order = "createdAt:DESC",
  ...filters
}: UseInternalIncomingRecordsParams) => {
  const { userDetails } = useAuthUser();
  const { permissionKeys } = useUserDetail(userDetails as MeDto);
  const RO = permissionKeys.includes("can:dispatchRecords");
  const incomingType = ["internal", "internal_memo", "direct"];
  // Base params
  const params: Record<string, any> = {
    recordType: incomingType,
    status: status ?? undefined,
    skip: pageIndex,
    take: pageSize,
    orderBy: order,
  };

  // Map searchQuery + filterType to backend param
  if (searchQuery) {
    switch (filterType) {
      case "Department":
        params.sendingPosition = searchQuery;
        break;
      case "Subject":
        params.subject = searchQuery;
        break;
      case "Date":
        params.fromCreatedAt = searchQuery; // or adapt depending on backend
        break;
      case "Reference Number":
        params.referenceNumber = searchQuery;
        break;
    }
  }

  // Merge additional filters
  Object.assign(params, filters);
  const v2Params = { ...params };
  delete v2Params.orderBy;

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: [
      "incoming-instances",
      pageIndex,
      pageSize,
      status,
      filterType,
      searchQuery,
      filters,
    ],
    queryFn: () => getIncoming(!RO ? params : {}),
    staleTime: 1000 * 60 * 5,
    enabled: Boolean(!RO),
  });
  const {
    data: dataV2,
    isLoading: isLoadingV2,
    isError: isErrorV2,
    refetch: refetchV2,
  } = useQuery({
    queryKey: [
      "incoming-instances/v2",
      pageIndex,
      pageSize,
      status,
      filterType,
      searchQuery,
      filters,
    ],
    queryFn: () => getIncomingV2(!RO ? v2Params : {}),
    staleTime: 1000 * 60 * 5,
    enabled: Boolean(!RO),
  });
  const {
    data: dataParent,
    isLoading: isLoadingParent,
    isError: isErrorParent,
    refetch: refetchParent,
  } = useQuery({
    queryKey: [
      "incoming-instances-parent",
      pageIndex,
      pageSize,
      status,
      filterType,
      searchQuery,
      filters,
    ],
    queryFn: () => getIncomingParent(fetchParent ? params : {}),
    staleTime: 1000 * 60 * 5,
    enabled: Boolean(fetchParent),
  });
  const internalRecords = data?.items ?? [];
  const InternalCount = data?.count ?? 0;
  const internalRecords2 = dataV2?.items ?? [];
  const InternalCount2 = dataV2?.count ?? 0;

  // Mutation for fetching attachments
  const {
    mutate: fetchAttachments,
    data: attachmentsData,
    isError: isAttachmentsError,
    isPending: isAttachmentsLoading,
  } = useMutation({
    mutationFn: (recordId: string) => fetchAttachment(recordId),
  });

  return {
    InternalCount,
    internalRecords,
    internalRecords2,
    InternalCount2,
    fetchAttachments,
    attachmentsData,
    isAttachmentsError,
    isAttachmentsLoading,
    isLoading,
    refetchV2,
    isLoadingV2,
    isErrorV2,
    isError,
    refetch,
    ...(fetchParent
      ? {
          internalParent: dataParent?.items ?? [],
          internalParentCount: dataParent?.count ?? 0,
          refetchParent,
          isErrorParent,
          isLoadingParent,
        }
      : {}),
  };
};
