import { useQuery } from '@tanstack/react-query';
import {
  checkInZone,
  clearTodayZoneCheckin,
  getTodayZoneCheckin,
  getZoneCheckinCompletion,
  listZoneCheckinHistory,
} from '@/shared/api/zoneCheckins';
import { getApiListRows } from '@/shared/business/apiListRows';
import { useInvalidatingMutation } from '@/shared/business/queryMutations';
import type { ZoneColor } from '@/shared/types/app';

export const ZONE_CHECKIN_QUERY_KEYS = {
  today: ['zoneCheckin', 'today'],
  history: ['zoneCheckin', 'history'],
  completion: (scopeKey: string | null) => ['zoneCheckin', 'completion', scopeKey],
} as const;

/**
 * Today's Zone check-in for the caller. "Today" is resolved server-side in the
 * campus timezone, so this hook never computes a date.
 */
export function useTodayZoneCheckIn(options: { readonly enabled?: boolean } = {}) {
  const enabled = options.enabled ?? true;
  const todayQuery = useQuery({
    queryKey: ZONE_CHECKIN_QUERY_KEYS.today,
    queryFn: getTodayZoneCheckin,
    enabled,
    retry: false,
  });

  const saveMutation = useInvalidatingMutation({
    mutationFn: (zone: ZoneColor) => checkInZone(zone),
    invalidateQueryKey: ZONE_CHECKIN_QUERY_KEYS.today,
  });

  const clearMutation = useInvalidatingMutation({
    mutationFn: () => clearTodayZoneCheckin(),
    invalidateQueryKey: ZONE_CHECKIN_QUERY_KEYS.today,
  });

  return {
    todayDate: enabled ? todayQuery.data?.date ?? null : null,
    todayZone: enabled ? todayQuery.data?.zone ?? null : null,
    isCheckedInToday: enabled ? todayQuery.data?.isCheckedInToday ?? false : false,
    isLoading: enabled && todayQuery.isLoading,
    isSaving: saveMutation.isPending || clearMutation.isPending,
    // Only surface actionable mutation (save/clear) errors. The today-load query
    // can 403 for a non-eligible role or before seeding; that is non-actionable
    // for the user and must not render as a scary "Forbidden" in the widget.
    error: saveMutation.error || clearMutation.error,
    setZone: (zone: ZoneColor) => saveMutation.mutateAsync(zone),
    clearToday: () => clearMutation.mutateAsync(),
  };
}

/** The caller's daily check-in history (most-recent first). */
export function useZoneCheckInHistory() {
  return useQuery({
    queryKey: ZONE_CHECKIN_QUERY_KEYS.history,
    queryFn: () => getApiListRows(listZoneCheckinHistory()),
    retry: false,
  });
}

/** Today's zone check-in completion report for the current leadership scope. */
export function useZoneCheckInCompletion(enabled: boolean, scopeKey: string | null) {
  return useQuery({
    queryKey: ZONE_CHECKIN_QUERY_KEYS.completion(scopeKey),
    queryFn: getZoneCheckinCompletion,
    enabled,
    retry: false,
  });
}
