import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { message } from 'antd';
import { experienceApi, type CreateExperienceDto } from '../infrastructure/experience.api';

export const EXPERIENCE_QUERY_KEY = 'pending-experiences';
export const EXPERIENCE_STATS_KEY = 'experience-stats';

export function usePendingExperiences(type?: string, enabled: boolean = true) {
  return useQuery({
    queryKey: [EXPERIENCE_QUERY_KEY, type],
    queryFn: () => experienceApi.getPendingExperiences(type),
    enabled,
  });
}

export function useExperienceStatistics() {
  return useQuery({
    queryKey: [EXPERIENCE_STATS_KEY],
    queryFn: () => experienceApi.getStatistics(),
  });
}

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

  return useMutation({
    mutationFn: ({ id, adminId }: { id: string; adminId: string }) =>
      experienceApi.approveExperience(id, adminId),
    onSuccess: () => {
      message.success('经验已批准');
      queryClient.invalidateQueries({ queryKey: [EXPERIENCE_QUERY_KEY] });
      queryClient.invalidateQueries({ queryKey: [EXPERIENCE_STATS_KEY] });
    },
  });
}

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

  return useMutation({
    mutationFn: ({ id, adminId }: { id: string; adminId: string }) =>
      experienceApi.rejectExperience(id, adminId),
    onSuccess: () => {
      message.success('经验已拒绝');
      queryClient.invalidateQueries({ queryKey: [EXPERIENCE_QUERY_KEY] });
      queryClient.invalidateQueries({ queryKey: [EXPERIENCE_STATS_KEY] });
    },
  });
}

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

  return useMutation({
    mutationFn: (dto: CreateExperienceDto) =>
      experienceApi.createExperience(dto),
    onSuccess: () => {
      message.success('经验已创建并自动激活');
      queryClient.invalidateQueries({ queryKey: [EXPERIENCE_QUERY_KEY] });
      queryClient.invalidateQueries({ queryKey: [EXPERIENCE_STATS_KEY] });
    },
    onError: () => {
      message.error('创建经验失败');
    },
  });
}

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

  return useMutation({
    mutationFn: (params?: { hoursBack?: number; limit?: number }) =>
      experienceApi.runEvolution(params?.hoursBack, params?.limit),
    onSuccess: (result) => {
      message.success(
        `进化任务完成：分析了${result.conversationsAnalyzed}个对话，提取了${result.experiencesExtracted}条经验`
      );
      queryClient.invalidateQueries({ queryKey: [EXPERIENCE_QUERY_KEY] });
      queryClient.invalidateQueries({ queryKey: [EXPERIENCE_STATS_KEY] });
    },
  });
}
