import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '../lib/api';
import type { ReviewNoteCreateRequest, ReviewNoteUpdateRequest } from '../types/api';

/**
 * Hook to fetch review notes for a job, optionally filtered by asset key.
 */
export function useReviewNotes(jobId: string, assetKey?: string) {
  return useQuery({
    queryKey: ['review-notes', jobId, assetKey],
    queryFn: () => apiClient.getReviewNotes(jobId, assetKey),
    enabled: !!jobId,
    staleTime: 10000, // 10 seconds
    refetchInterval: 30000, // Poll every 30s for other reviewers' notes
    refetchOnWindowFocus: true,
  });
}

/**
 * Hook to create a new review note.
 */
export function useCreateReviewNote() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ jobId, data }: { jobId: string; data: ReviewNoteCreateRequest }) =>
      apiClient.createReviewNote(jobId, data),
    onSuccess: (_, { jobId, data }) => {
      // Invalidate notes list for this job and asset
      queryClient.invalidateQueries({ queryKey: ['review-notes', jobId, data.asset_key] });
      // Also invalidate the unfiltered list
      queryClient.invalidateQueries({ queryKey: ['review-notes', jobId, undefined] });
    },
  });
}

/**
 * Hook to update an existing review note.
 */
export function useUpdateReviewNote() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ jobId, noteId, data }: { jobId: string; noteId: string; data: ReviewNoteUpdateRequest }) =>
      apiClient.updateReviewNote(jobId, noteId, data),
    onSuccess: (_, { jobId }) => {
      // Invalidate all notes for this job (we don't know the asset key here)
      queryClient.invalidateQueries({ queryKey: ['review-notes', jobId] });
    },
  });
}

/**
 * Hook to delete a review note.
 */
export function useDeleteReviewNote() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ jobId, noteId }: { jobId: string; noteId: string }) =>
      apiClient.deleteReviewNote(jobId, noteId),
    onSuccess: (_, { jobId }) => {
      // Invalidate all notes for this job
      queryClient.invalidateQueries({ queryKey: ['review-notes', jobId] });
    },
  });
}
