import { useQuery } from "@tanstack/react-query";
import {
  getIncomingReport,
  getReport,
  Report,
  getReportRO,
  ReportRO,
} from "@/record-management/services/api/reportService";
import { MeDto } from "@/shared/dto/user/meDto";
import { useUserDetail } from "./useUserDetail";
import { useAuthUser } from "@/record-management/hooks/useAuthUser";

export interface ReportIncoming {
  status: string;
  count: number;
}

export const useReport = (id: string) => {
  const { userDetails } = useAuthUser();
  const { isRO } = useUserDetail(userDetails as MeDto);
  const { data, isLoading, isError, refetch } = useQuery<ReportIncoming[]>({
    queryKey: ["report", id],
    queryFn: () => getIncomingReport(id),
    staleTime: 60 * 1000, // cache for 1 minute
    enabled: !!id, // only run if id is truthy
  });
  const { data: dashboard } = useQuery<Report>({
    queryKey: ["dashbordReport"],
    queryFn: () => getReport(),
    staleTime: 60 * 1000, // cache for 1 minute
    enabled: Boolean(!isRO), // only run if id is truthy
  });
  const { data: ROdashboard } = useQuery<ReportRO>({
    queryKey: ["dashbordReportRO"],
    queryFn: () => getReportRO(),
    staleTime: 60 * 1000, // cache for 1 minute
    enabled: Boolean(isRO), // only run if ro is truthy
  });
  const report = data ?? []; // ensure we always return an array
  // Calculate Total For User

  // internal and internal memo
  const employeeDraftForYourReference =
    dashboard?.incomingStatusCountByEmployee?.for_your_reference?.draft || 0;
  const positionDraftForYourReference =
    dashboard?.incomingStatusCountByPosition?.for_your_reference?.draft || 0;

  const employeeDraftInternal =
    dashboard?.incomingStatusCountByEmployee?.internal?.draft || 0;
  const positionDraftinternal =
    dashboard?.incomingStatusCountByPosition?.internal?.draft || 0;
  const employeeDraftInternalMemo =
    dashboard?.incomingStatusCountByEmployee?.internal_memo?.draft || 0;
  const positionDraftinternalMemo =
    dashboard?.incomingStatusCountByPosition?.internal_memo?.draft || 0;
  const TotalDraftInternal =
    employeeDraftInternal +
    positionDraftinternal +
    employeeDraftInternalMemo +
    positionDraftinternalMemo;
  const TotalDraftForYourRef =
    employeeDraftForYourReference + positionDraftForYourReference;
  const UrgentemployeeDraftInternal =
    dashboard?.incomingStatusCountByEmployee?.internal?.urgent?.draft || 0;
  const UrgentpositionDraftInternal =
    dashboard?.incomingStatusCountByPosition?.internal?.urgent?.draft || 0;
  const UrgentemployeeDraftInternalMemo =
    dashboard?.incomingStatusCountByEmployee?.internal_memo?.urgent?.draft || 0;
  const UrgentpositionDraftInternalMemo =
    dashboard?.incomingStatusCountByPosition?.internal_memo?.urgent?.draft || 0;
  const TotalUrgentDraftInternal =
    UrgentemployeeDraftInternal +
    UrgentpositionDraftInternal +
    UrgentemployeeDraftInternalMemo +
    UrgentpositionDraftInternalMemo;
  // external
  const employeeDraftNonSmartUser =
    dashboard?.incomingStatusCountByEmployee?.non_smart_user?.draft || 0;
  const positionDraftNonSmartUser =
    dashboard?.incomingStatusCountByPosition?.non_smart_user?.draft || 0;
  const employeeDraftExternalNonSmartUser =
    dashboard?.incomingStatusCountByEmployee?.external_non_smart_user?.draft ||
    0;
  const positionDraftExternalNonSmartUser =
    dashboard?.incomingStatusCountByPosition?.external_non_smart_user?.draft ||
    0;
  const employeeDraftExternal =
    dashboard?.incomingStatusCountByEmployee?.external?.draft || 0;
  const positionDraftExternal =
    dashboard?.incomingStatusCountByPosition?.external?.draft || 0;
  const TotalDraftsNonSmart =
    employeeDraftNonSmartUser + positionDraftNonSmartUser;
  const TotalDraftsExternalNonSmart =
    employeeDraftExternalNonSmartUser + positionDraftExternalNonSmartUser;
  const TotalDraftsExternal = employeeDraftExternal + positionDraftExternal;
  const TotalDraftExternal =
    TotalDraftsExternal + TotalDraftsExternalNonSmart + TotalDraftsNonSmart;
  const TotalDraftCC = dashboard?.incomingCCCounts?.Unseen || 0;
  const UrgentemployeeDraftNonSmart =
    dashboard?.incomingStatusCountByEmployee?.non_smart_user?.urgent?.draft ||
    0;
  const UrgentpositionDraftNonSmart =
    dashboard?.incomingStatusCountByPosition?.non_smart_user?.urgent?.draft ||
    0;
  const UrgentemployeeDraftExternalNonSmart =
    dashboard?.incomingStatusCountByEmployee?.external_non_smart_user?.urgent
      ?.draft || 0;
  const UrgentpositionDraftExternalNonSmart =
    dashboard?.incomingStatusCountByPosition?.external_non_smart_user?.urgent
      ?.draft || 0;
  const UrgentemployeeDraftExternal =
    dashboard?.incomingStatusCountByEmployee?.external?.urgent?.draft || 0;
  const UrgentpositionDraftExternal =
    dashboard?.incomingStatusCountByPosition?.external?.urgent?.draft || 0;
  const TotalUrgentDraftExternal =
    UrgentemployeeDraftExternal +
    UrgentpositionDraftExternal +
    UrgentemployeeDraftExternalNonSmart +
    UrgentpositionDraftExternalNonSmart +
    UrgentemployeeDraftNonSmart +
    UrgentpositionDraftNonSmart;
  // Calculate Total For RO
  const ROIncomingNonSmart =
    ROdashboard?.recordCount?.non_smart_user?.not_assigned || 0;
  const ROIncomingExternalNonSmart =
    ROdashboard?.recordCount?.external_non_smart_user?.not_assigned || 0;
  const ROIncomingSmart = ROdashboard?.recordBoxCount?.draft || 0;
  const ROTotalDraftIncoming =
    ROIncomingNonSmart + ROIncomingExternalNonSmart + ROIncomingSmart;
  const ROPending = ROdashboard?.outgoingInstanceCount?.Approved || 0;
  const ROPendingUrgent =
    ROdashboard?.outgoingInstanceCount?.urgent?.Approved || 0;
  const totalOutgoing = ROdashboard?.outgoingInstanceCount?.Dispatched || 0;
  const totalArrayIncoming = [ROdashboard?.recordCount];
  const smartIncomingArray = [ROdashboard?.recordBoxCount];
  const totalIncomingSmart = smartIncomingArray.reduce((acc, item) => {
    if (!item) return acc;

    const itemSum = Object.values(item)
      .filter((value) => typeof value === "number")
      .reduce((sum, num) => sum + num, 0);

    return acc + itemSum;
  }, 0);

  const totalIncoming = totalArrayIncoming.reduce((acc, item) => {
    if (!item) return acc;

    const itemSum = Object.entries(item)
      .filter(
        ([key]) =>
          key !== "internal" && key !== "internal_memo" && key !== "external",
      )
      .flatMap(([_, obj]) => Object.values(obj))
      .reduce((sum, num) => sum + num, 0);

    return acc + itemSum;
  }, 0);
  return {
    report,
    isLoading,
    isError,
    refetch,
    dashboard,
    ROdashboard,
    TotalDraftInternal,
    TotalDraftExternal,
    TotalDraftCC,
    TotalDraftsExternal,
    TotalDraftsExternalNonSmart,
    TotalDraftsNonSmart,
    ROIncomingNonSmart,
    ROIncomingExternalNonSmart,
    ROTotalDraftIncoming,
    ROIncomingSmart,
    ROPending,
    TotalUrgentDraftInternal,
    TotalUrgentDraftExternal,
    ROPendingUrgent,
    ROTotalIncoming: totalIncoming + totalIncomingSmart,
    ROTotalOutgoing: totalOutgoing,
    TotalDraftForYourRef,
  };
};
