import { useQuery, useMutation } from "@tanstack/react-query";
import {
  tradingClient,
  riskClient,
  mlClient,
  mlTrainingClient,
  configClient,
  monitoringClient,
  backtestingClient,
} from "../lib/grpc";
import type { OrderSide, OrderType } from "../gen/trading_pb";

// ---------------------------------------------------------------------------
// Trading
// ---------------------------------------------------------------------------

export function usePositions() {
  return useQuery({
    queryKey: ["positions"],
    queryFn: () => tradingClient.getPositions({}),
    refetchInterval: 5000,
  });
}

export function useOrders() {
  return useQuery({
    queryKey: ["orders"],
    queryFn: () => tradingClient.getOrderStatus({}),
    refetchInterval: 5000,
  });
}

export function useOrderBook(symbol: string) {
  return useQuery({
    queryKey: ["order-book", symbol],
    queryFn: () => tradingClient.getOrderBook({ symbol }),
    refetchInterval: 2000,
  });
}

export function useSubmitOrder() {
  return useMutation({
    mutationFn: (order: {
      symbol: string;
      side: OrderSide;
      orderType: OrderType;
      quantity: number;
      price?: number;
    }) => tradingClient.submitOrder(order),
  });
}

export function useMlPredictions() {
  return useQuery({
    queryKey: ["ml-predictions"],
    queryFn: () => tradingClient.getMLPredictions({}),
    refetchInterval: 5000,
  });
}

// ---------------------------------------------------------------------------
// Risk
// ---------------------------------------------------------------------------

export function useRiskMetrics() {
  return useQuery({
    queryKey: ["risk-metrics"],
    queryFn: () => riskClient.getRiskMetrics({}),
    refetchInterval: 5000,
  });
}

export function useEmergencyStop() {
  return useMutation({
    mutationFn: (params: { reason?: string }) =>
      riskClient.emergencyStop(params),
  });
}

// ---------------------------------------------------------------------------
// ML
// ---------------------------------------------------------------------------

export function useMlPrediction() {
  return useQuery({
    queryKey: ["ml-prediction"],
    queryFn: () => mlClient.getPrediction({}),
    refetchInterval: 5000,
  });
}

// ---------------------------------------------------------------------------
// Training
// ---------------------------------------------------------------------------

export function useTrainingJobs() {
  return useQuery({
    queryKey: ["training-jobs"],
    queryFn: () => mlTrainingClient.listTrainingJobs({}),
    refetchInterval: 5000,
  });
}

// ---------------------------------------------------------------------------
// Performance / Monitoring
// ---------------------------------------------------------------------------

export function usePerformanceMetrics() {
  return useQuery({
    queryKey: ["performance-metrics"],
    queryFn: () => monitoringClient.getMetrics({}),
    refetchInterval: 10000,
  });
}

export function useSystemStatus() {
  return useQuery({
    queryKey: ["system-status"],
    queryFn: () => monitoringClient.getSystemStatus({}),
    refetchInterval: 10000,
  });
}

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------

export function useConfig() {
  return useQuery({
    queryKey: ["config"],
    queryFn: () => configClient.getConfiguration({}),
  });
}

export function useUpdateConfig() {
  return useMutation({
    mutationFn: (params: {
      key: string;
      value: string;
      category?: string;
    }) => configClient.updateConfiguration(params),
  });
}

// ---------------------------------------------------------------------------
// Backtesting
// ---------------------------------------------------------------------------

export function useStartBacktest() {
  return useMutation({
    mutationFn: (params: {
      strategy: string;
      symbol: string;
      startDate: string;
      endDate: string;
    }) =>
      backtestingClient.startBacktest({
        strategyName: params.strategy,
        symbols: [params.symbol],
        startDateUnixNanos: BigInt(new Date(params.startDate).getTime()) * 1_000_000n,
        endDateUnixNanos: BigInt(new Date(params.endDate).getTime()) * 1_000_000n,
      }),
  });
}

export function useBacktestStatus(backtestId: string | null) {
  return useQuery({
    queryKey: ["backtest-status", backtestId],
    queryFn: () =>
      backtestingClient.getBacktestStatus({ backtestId: backtestId! }),
    enabled: backtestId !== null,
    refetchInterval: 2000,
  });
}

export function useBacktestResults(
  backtestId: string | null,
  enabled: boolean,
) {
  return useQuery({
    queryKey: ["backtest-results", backtestId],
    queryFn: () =>
      backtestingClient.getBacktestResults({ backtestId: backtestId! }),
    enabled,
  });
}
