"use client";

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

import {
  getDashboardSummary,
  type DashboardSummary,
  type DashboardSummaryParams,
} from "../service/cdc-gpsf-dashboard-service";

// Safe zeros to show while loading or when a request fails.
const EMPTY_SUMMARY: DashboardSummary = {
  cards: {
    totalIssues: 0,
    solved: 0,
    inProgress: 0,
    notAddressed: 0,
    totalPrimaryAgencies: 0,
  },
  statusBreakdown: [],
  byPrimaryAgency: [],
  byWorkingGroup: [],
  byCategory: [],
};

// Dashboard numbers change rarely, so keep results fresh for 5 minutes.
// This also means the UNfiltered summary (used for the Working Group
// dropdown options below) is served from cache instead of refetching
// every time the user changes a filter.
const SUMMARY_STALE_TIME_MS = 5 * 60 * 1000;

const cdcGpsfDashboardQueryKeys = {
  all: ["cdc-gpsf-dashboard"] as const,
  workingGroup: (params: DashboardSummaryParams) =>
    [...cdcGpsfDashboardQueryKeys.all, "working-group", params] as const,
};

function getErrorMessage(error: unknown, fallback: string) {
  return error instanceof Error ? error.message : fallback;
}

export function useCdcGpsfDashboardSummary(params: DashboardSummaryParams) {
  const query = useQuery({
    queryKey: cdcGpsfDashboardQueryKeys.workingGroup(params),
    queryFn: () => getDashboardSummary(params),
    staleTime: SUMMARY_STALE_TIME_MS,
  });

  return {
    summary: query.data ?? EMPTY_SUMMARY,
    isLoading: query.isLoading,
    error: query.error
      ? getErrorMessage(query.error, "Unable to load the dashboard.")
      : null,
  };
}

// The Working Group dropdown has no dedicated lookup endpoint, so we take
// the names from the UNfiltered summary. On first page load (no filters
// applied) this is the exact same query as the main dashboard call, so it
// costs no extra network request.
export function useCdcGpsfWorkingGroupOptions() {
  const { summary } = useCdcGpsfDashboardSummary({});

  return summary.byWorkingGroup.map((group) => ({
    label: group.workingGroupName,
    value: String(group.workingGroupId),
  }));
}
