import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '../lib/api';
import type {
  Job,
  JobCreateRequest,
  VttUpdateRequest,
  BulkDeleteRequest,
  TTSPreferences
} from '../types/api';

// Query hooks
export function useJobs(filters?: { status?: string; mine?: boolean; page?: number; size?: number }, options?: { enabled?: boolean }) {
  return useQuery({
    queryKey: ['jobs', filters],
    queryFn: () => apiClient.getJobs(filters),
    enabled: options?.enabled ?? true,
  });
}

export function useJob(jobId: string) {
  return useQuery({
    queryKey: ['jobs', jobId],
    queryFn: () => apiClient.getJob(jobId),
    enabled: !!jobId,
    staleTime: 30000, // 30 seconds
    refetchOnWindowFocus: false,
  });
}

export function useJobDownloads(jobId: string) {
  return useQuery({
    queryKey: ['jobs', jobId, 'downloads'],
    queryFn: () => apiClient.getJobDownloads(jobId),
    enabled: !!jobId,
    staleTime: 30000, // 30 seconds
    refetchOnWindowFocus: false,
  });
}

export function useJobVttContent(jobId: string, language?: string) {
  return useQuery({
    queryKey: ['jobs', jobId, 'vtt', language || 'source'],
    queryFn: () => apiClient.getJobVttContent(jobId, language),
    enabled: !!jobId,
    staleTime: 30000, // 30 seconds
    refetchOnWindowFocus: false,
  });
}

export function useJobValidation(jobId: string) {
  return useQuery({
    queryKey: ['jobs', jobId, 'validation'],
    queryFn: () => apiClient.validateJobAssets(jobId),
    enabled: !!jobId,
  });
}

// Mutation hooks
export function useCreateJob() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ data, file, onUploadProgress }: { 
      data: JobCreateRequest; 
      file: File; 
      onUploadProgress?: (progressEvent: { loaded: number; total: number }) => void 
    }) =>
      apiClient.createJob(data, file, onUploadProgress),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}

export function useUpdateJob() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<Job> }) =>
      apiClient.updateJob(id, data),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ['jobs', id] });
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}

export function useApproveEnglish() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, notes, tts_preferences }: { id: string; notes?: string; tts_preferences?: TTSPreferences }) =>
      apiClient.approveSource(id, notes, tts_preferences),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ['jobs', id] });
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}

export function useApproveSource() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, notes, tts_preferences }: { id: string; notes?: string; tts_preferences?: TTSPreferences }) =>
      apiClient.approveSource(id, notes, tts_preferences),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ['jobs', id] });
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}

export function useRejectJob() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, notes }: { id: string; notes: string }) =>
      apiClient.rejectJob(id, notes),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ['jobs', id] });
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}

export function useCompleteJob() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, notes }: { id: string; notes?: string }) =>
      apiClient.completeJob(id, notes),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ['jobs', id] });
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}

export function useUpdateJobVtt() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: VttUpdateRequest }) =>
      apiClient.updateJobVttContent(id, data),
    onSuccess: (_, { id, data }) => {
      queryClient.invalidateQueries({ queryKey: ['jobs', id] });
      // Invalidate the VTT cache for the specific language or 'source' if not specified
      queryClient.invalidateQueries({ queryKey: ['jobs', id, 'vtt', data.language || 'source'] });
    },
  });
}

export function useRejectFinalReview() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, notes }: { id: string; notes: string }) =>
      apiClient.rejectFinalReview(id, notes),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ['jobs', id] });
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}

export function useDeleteJob() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (id: string) => apiClient.deleteJob(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}

export function useBulkDeleteJobs() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (data: BulkDeleteRequest) => apiClient.bulkDeleteJobs(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}

export function useAdjustVttTiming() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, offsetSeconds, language = 'en', adjustCaptions = true, adjustAudioDescription = true }: { 
      id: string; 
      offsetSeconds: number;
      language?: string;
      adjustCaptions?: boolean;
      adjustAudioDescription?: boolean;
    }) =>
      apiClient.adjustVttTiming(id, {
        offset_seconds: offsetSeconds,
        language,
        adjust_captions: adjustCaptions,
        adjust_audio_description: adjustAudioDescription,
      }),
    onSuccess: (_, { id, language }) => {
      queryClient.invalidateQueries({ queryKey: ['jobs', id] });
      queryClient.invalidateQueries({ queryKey: ['jobs', id, 'vtt', language] });
    },
  });
}

export function useReprocessJob() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (id: string) => apiClient.reprocessJob(id),
    onSuccess: (_, id) => {
      // Invalidate both the specific job and the jobs list to reflect status changes
      queryClient.invalidateQueries({ queryKey: ['jobs', id] });
      queryClient.invalidateQueries({ queryKey: ['jobs'] });
    },
  });
}