import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api/apiClient';
import { showSuccess, handleError } from '@/lib/services/errorHandler';

// Query Keys
export const adminTaskKeys = {
  all: ['admin', 'tasks'] as const,
  lists: () => [...adminTaskKeys.all, 'list'] as const,
  list: (filters: Record<string, unknown>) => [...adminTaskKeys.lists(), filters] as const,
  stats: () => [...adminTaskKeys.all, 'stats'] as const,
  queue: () => [...adminTaskKeys.all, 'queue'] as const,
  detail: (id: string) => [...adminTaskKeys.all, 'detail', id] as const,
};

// Types (apiClient automatically converts snake_case to camelCase)
export type TaskStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled';
export type TaskType = 'image' | 'video' | 'audio' | 'script' | 'other';

export interface TaskResult {
  url?: string;
  imageUrl?: string;
  videoUrl?: string;
  audioUrl?: string;
  prompt?: string;
  negativePrompt?: string;
  model?: string;
  provider?: string;
  durationSeconds?: number;
  fileSize?: number;
  resolution?: string;
  format?: string;
  providerTaskId?: string;
  cost?: number;
  creditsUsed?: number;
  createdAt?: string;
  metadata?: Record<string, unknown>;
}

export interface AdminTask {
  id: string;
  type: TaskType;
  status: TaskStatus;
  projectId?: string;
  projectName?: string;
  userId?: string;
  userEmail?: string;
  userName?: string;
  createdAt: string;
  startedAt?: string;
  completedAt?: string;
  duration?: number; // in seconds
  error?: string;
  progress?: number;
  metadata?: Record<string, unknown>;
}

export interface AdminTaskDetail extends AdminTask {
  model?: string;
  provider?: string;
  retryCount: number;
  maxRetries: number;
  result?: TaskResult;
  params?: Record<string, unknown>;
}

export interface AdminTasksResponse {
  items: AdminTask[];
  pagination: {
    page: number;
    page_size: number;
    total: number;
    total_pages: number;
  };
}

export interface TaskStats {
  total: number;
  pending: number;
  processing: number;
  completed: number;
  failed: number;
  cancelled: number;
  avgDuration?: number;
}

export interface QueueStatus {
  queueLength: number;
  activeWorkers: number;
  maxWorkers: number;
  throughputPerMinute: number;
  estimatedWaitSeconds: number;
}

export interface AdminTaskFilters {
  page?: number;
  page_size?: number;
  status?: TaskStatus;
  type?: TaskType;
  user_id?: string;
  project_id?: string;
  [key: string]: undefined | number | string | TaskStatus | TaskType;
}

// Hooks
export function useAdminTasks(filters: AdminTaskFilters = {}) {
  const { page = 1, page_size = 20, status, type, user_id, project_id } = filters;

  return useQuery({
    queryKey: adminTaskKeys.list(filters),
    queryFn: async () => {
      const params = new URLSearchParams();
      params.append('page', String(page));
      params.append('page_size', String(page_size));
      if (status) params.append('status', status);
      if (type) params.append('type', type);
      if (user_id) params.append('user_id', user_id);
      if (project_id) params.append('project_id', project_id);

      const response = await api.get(`/api/v1/admin/tasks?${params.toString()}`);
      // Backend returns: { code, data: { items, pagination }, meta }
      // apiClient automatically converts snake_case to camelCase
      const data = response.data?.data ?? response.data;
      return {
        items: (data as any)?.items || [],
        pagination: (data as any)?.pagination || {}
      } as AdminTasksResponse;
    },
    staleTime: 10 * 1000, // 10 seconds - tasks change frequently
    refetchInterval: 30 * 1000, // Auto refresh every 30 seconds
  });
}

export function useAdminTaskStats() {
  return useQuery({
    queryKey: adminTaskKeys.stats(),
    queryFn: async () => {
      const response = await api.get('/api/v1/admin/tasks/stats');
      const data = response.data?.data ?? response.data;
      return data as TaskStats;
    },
    staleTime: 10 * 1000,
    refetchInterval: 30 * 1000,
  });
}

export function useAdminTaskQueue() {
  return useQuery({
    queryKey: adminTaskKeys.queue(),
    queryFn: async () => {
      const response = await api.get('/api/v1/admin/tasks/queue');
      const data = response.data?.data ?? response.data;
      return data as QueueStatus;
    },
    staleTime: 5 * 1000,
    refetchInterval: 10 * 1000,
  });
}

export function useAdminTaskDetail(taskId: string | null) {
  return useQuery({
    queryKey: adminTaskKeys.detail(taskId || ''),
    queryFn: async () => {
      if (!taskId) return null;
      const response = await api.get(`/api/v1/admin/tasks/${taskId}`);
      const data = response.data?.data ?? response.data;
      // apiClient automatically converts snake_case to camelCase
      // Backend returns AdminTaskDetailResponse with result info
      return data as AdminTaskDetail;
    },
    enabled: !!taskId,
    staleTime: 5 * 1000,
    refetchInterval: 10 * 1000,
  });
}

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

  return useMutation({
    mutationFn: async (taskId: string) => {
      const response = await api.post(`/api/v1/admin/tasks/${taskId}/retry`);
      return response.data;
    },
    onSuccess: () => {
      showSuccess('重试成功', '任务已重新加入队列');
      queryClient.invalidateQueries({ queryKey: adminTaskKeys.all });
    },
    onError: (error) => {
      handleError(error, 'RetryAdminTask', {
        customMessage: '重试任务失败，请重试',
      });
    },
  });
}

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

  return useMutation({
    mutationFn: async (taskId: string) => {
      await api.delete(`/api/v1/admin/tasks/${taskId}`);
      return taskId;
    },
    onSuccess: () => {
      showSuccess('删除成功', '任务已成功删除');
      queryClient.invalidateQueries({ queryKey: adminTaskKeys.all });
    },
    onError: (error) => {
      handleError(error, 'DeleteAdminTask', {
        customMessage: '删除任务失败，请重试',
      });
    },
  });
}
