/**
 * @ai-summary React Query hooks for Community Gas Stations feature
 */

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { communityStationsApi } from '../api/community-stations.api';
import { SubmitStationData, ReviewDecision, StationBounds } from '../types/community-stations.types';

// Query keys
export const communityStationsKeys = {
  all: ['community-stations'] as const,
  submissions: ['community-stations', 'submissions'] as const,
  mySubmissions: ['community-stations', 'my-submissions'] as const,
  approved: ['community-stations', 'approved'] as const,
  nearby: ['community-stations', 'nearby'] as const,
  bounds: ['community-stations', 'bounds'] as const,
  adminAll: ['community-stations', 'admin', 'all'] as const,
  adminPending: ['community-stations', 'admin', 'pending'] as const,
};

/**
 * Hook to submit a new community gas station
 * Note: Submissions are now auto-approved
 */
export const useSubmitStation = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: SubmitStationData) => communityStationsApi.submitStation(data),
    onSuccess: () => {
      // Invalidate all relevant caches since submissions are auto-approved
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.mySubmissions });
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.approved });
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.nearby });
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.bounds });
    },
  });
};

/**
 * Hook to get user's submitted stations
 */
export const useMySubmissions = () => {
  return useQuery({
    queryKey: communityStationsKeys.mySubmissions,
    queryFn: () => communityStationsApi.getMySubmissions(),
  });
};

/**
 * Hook to withdraw a submission
 */
export const useWithdrawSubmission = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => communityStationsApi.withdrawSubmission(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.mySubmissions });
    },
  });
};

/**
 * Hook to get approved community stations
 */
export const useApprovedStations = (page: number = 0, limit: number = 50) => {
  return useQuery({
    queryKey: [...communityStationsKeys.approved, page, limit],
    queryFn: () => communityStationsApi.getApprovedStations(page, limit),
  });
};

/**
 * Hook to get approved stations nearby
 */
export const useApprovedNearbyStations = (
  latitude: number | null,
  longitude: number | null,
  radiusMeters: number = 5000
) => {
  return useQuery({
    queryKey: [...communityStationsKeys.nearby, latitude, longitude, radiusMeters],
    queryFn: () => {
      if (latitude === null || longitude === null) {
        return Promise.resolve([]);
      }
      return communityStationsApi.getApprovedNearby(latitude, longitude, radiusMeters);
    },
    enabled: latitude !== null && longitude !== null,
  });
};

/**
 * Hook to get all submissions (admin)
 */
export const useAllCommunitySubmissions = (
  status?: string,
  page: number = 0,
  limit: number = 50
) => {
  return useQuery({
    queryKey: [...communityStationsKeys.adminAll, status, page, limit],
    queryFn: () => communityStationsApi.getAllSubmissions(status, page, limit),
  });
};

/**
 * Hook to get pending submissions (admin)
 */
export const usePendingSubmissions = (page: number = 0, limit: number = 50) => {
  return useQuery({
    queryKey: [...communityStationsKeys.adminPending, page, limit],
    queryFn: () => communityStationsApi.getPendingSubmissions(page, limit),
  });
};

/**
 * Hook to review a submission (admin)
 */
export const useReviewStation = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, decision }: { id: string; decision: ReviewDecision }) =>
      communityStationsApi.reviewStation(id, decision),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.adminPending });
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.adminAll });
    },
  });
};

/**
 * Hook to bulk review submissions (admin)
 */
export const useBulkReviewStations = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ ids, decision }: { ids: string[]; decision: ReviewDecision }) =>
      communityStationsApi.bulkReviewStations(ids, decision),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.adminPending });
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.adminAll });
    },
  });
};

/**
 * Hook to get approved stations within map bounds
 */
export const useApprovedStationsInBounds = (bounds: StationBounds | null) => {
  return useQuery({
    queryKey: [...communityStationsKeys.bounds, bounds],
    queryFn: () => {
      if (!bounds) {
        return Promise.resolve([]);
      }
      return communityStationsApi.getApprovedInBounds(bounds);
    },
    enabled: bounds !== null,
  });
};

/**
 * Hook to report a station as no longer having Premium 93
 */
export const useReportRemoval = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ stationId, reason }: { stationId: string; reason?: string }) =>
      communityStationsApi.reportRemoval(stationId, reason),
    onSuccess: () => {
      // Invalidate approved stations lists as station may have been removed
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.approved });
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.nearby });
      queryClient.invalidateQueries({ queryKey: communityStationsKeys.bounds });
    },
  });
};
