import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { message } from 'antd';
import {
  mcpApi,
  type McpServerDto,
  type McpServerDetailDto,
  type McpOverviewDto,
  type CreateMcpServerDto,
  type UpdateMcpServerDto,
  type McpToolDefinition,
  type TestConnectionResult,
} from '../infrastructure/mcp.api';

export function useMcpOverview() {
  return useQuery<McpOverviewDto>({
    queryKey: ['mcp', 'overview'],
    queryFn: () => mcpApi.getOverview(),
    refetchInterval: 10000,
  });
}

export function useMcpServers() {
  return useQuery<McpServerDto[]>({
    queryKey: ['mcp', 'servers'],
    queryFn: () => mcpApi.listServers(),
    refetchInterval: 5000,
  });
}

export function useMcpServer(id: string | null, enabled = true) {
  return useQuery<McpServerDetailDto>({
    queryKey: ['mcp', 'servers', id],
    queryFn: () => mcpApi.getServer(id!),
    enabled: enabled && !!id,
    refetchInterval: 5000,
  });
}

export function useMcpServerTools(id: string | null, enabled = true) {
  return useQuery<McpToolDefinition[]>({
    queryKey: ['mcp', 'servers', id, 'tools'],
    queryFn: () => mcpApi.getServerTools(id!),
    enabled: enabled && !!id,
  });
}

export function useCreateMcpServer() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (dto: CreateMcpServerDto) => mcpApi.createServer(dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mcp'] });
      message.success('MCP Server 创建成功');
    },
    onError: (error: any) => {
      message.error(error.response?.data?.message || '创建失败');
    },
  });
}

export function useUpdateMcpServer() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: UpdateMcpServerDto }) =>
      mcpApi.updateServer(id, dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mcp'] });
      message.success('MCP Server 更新成功');
    },
    onError: (error: any) => {
      message.error(error.response?.data?.message || '更新失败');
    },
  });
}

export function useDeleteMcpServer() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => mcpApi.deleteServer(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mcp'] });
      message.success('MCP Server 已删除');
    },
    onError: (error: any) => {
      message.error(error.response?.data?.message || '删除失败');
    },
  });
}

export function useConnectMcpServer() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => mcpApi.connectServer(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mcp'] });
      message.success('连接成功');
    },
    onError: (error: any) => {
      message.error(error.response?.data?.message || '连接失败');
    },
  });
}

export function useDisconnectMcpServer() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => mcpApi.disconnectServer(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mcp'] });
      message.success('已断开连接');
    },
    onError: (error: any) => {
      message.error(error.response?.data?.message || '断开失败');
    },
  });
}

export function useTestMcpServer() {
  return useMutation({
    mutationFn: (id: string) => mcpApi.testServer(id),
    onSuccess: (result: TestConnectionResult) => {
      if (result.success) {
        message.success(`连接测试成功！发现 ${result.toolCount} 个工具`);
      } else {
        message.error(`连接测试失败: ${result.error}`);
      }
    },
    onError: (error: any) => {
      message.error(error.response?.data?.message || '测试失败');
    },
  });
}

export function useTestMcpConfig() {
  return useMutation({
    mutationFn: (dto: CreateMcpServerDto) => mcpApi.testConfig(dto),
  });
}

// Re-export types for convenience
export type {
  McpServerDto,
  McpServerDetailDto,
  McpOverviewDto,
  McpToolDefinition,
  CreateMcpServerDto,
  UpdateMcpServerDto,
  McpTransportType,
  McpConnectionState,
  TestConnectionResult,
} from '../infrastructure/mcp.api';
