import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { message } from 'antd';
import {
  analyticsApi,
  type DailyStatisticsDto,
  type TrendData,
  type FinancialReportDto,
  type AuditLogQueryParams,
  type PaginatedAuditLogs,
} from '../infrastructure/analytics.api';

// ==================== Query Keys ====================

export const ANALYTICS_KEYS = {
  today: ['analytics', 'today'] as const,
  daily: (startDate: string, endDate: string, dimension?: string) =>
    ['analytics', 'daily', startDate, endDate, dimension] as const,
  trend: (days: number, metrics: string[]) =>
    ['analytics', 'trend', days, metrics] as const,
  byChannel: (startDate: string, endDate: string) =>
    ['analytics', 'by-channel', startDate, endDate] as const,
  byCategory: (startDate: string, endDate: string) =>
    ['analytics', 'by-category', startDate, endDate] as const,
};

export const REPORTS_KEYS = {
  list: (year?: number, status?: string) =>
    ['financial-reports', year, status] as const,
  detail: (month: string) =>
    ['financial-reports', month] as const,
};

export const AUDIT_KEYS = {
  logs: (params: AuditLogQueryParams) =>
    ['audit-logs', params] as const,
  detail: (id: string) =>
    ['audit-logs', id] as const,
  actionTypes: ['audit-logs', 'action-types'] as const,
  entityTypes: ['audit-logs', 'entity-types'] as const,
};

// ==================== Statistics Hooks ====================

export function useTodayStatistics() {
  return useQuery({
    queryKey: ANALYTICS_KEYS.today,
    queryFn: analyticsApi.getTodayStatistics,
    refetchInterval: 5 * 60 * 1000, // Refresh every 5 minutes
  });
}

export function useDailyStatistics(
  startDate: string,
  endDate: string,
  dimension?: string,
  enabled = true
) {
  return useQuery({
    queryKey: ANALYTICS_KEYS.daily(startDate, endDate, dimension),
    queryFn: () => analyticsApi.getDailyStatistics(startDate, endDate, dimension),
    enabled: enabled && !!startDate && !!endDate,
  });
}

export function useTrendData(
  days = 7,
  metrics = ['newConversations', 'newUsers']
) {
  return useQuery({
    queryKey: ANALYTICS_KEYS.trend(days, metrics),
    queryFn: () => analyticsApi.getTrendData(days, metrics),
  });
}

export function useStatisticsByChannel(startDate: string, endDate: string, enabled = true) {
  return useQuery({
    queryKey: ANALYTICS_KEYS.byChannel(startDate, endDate),
    queryFn: () => analyticsApi.getStatisticsByChannel(startDate, endDate),
    enabled: enabled && !!startDate && !!endDate,
  });
}

export function useStatisticsByCategory(startDate: string, endDate: string, enabled = true) {
  return useQuery({
    queryKey: ANALYTICS_KEYS.byCategory(startDate, endDate),
    queryFn: () => analyticsApi.getStatisticsByCategory(startDate, endDate),
    enabled: enabled && !!startDate && !!endDate,
  });
}

export function useRefreshStatistics() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (date?: string) => analyticsApi.refreshStatistics(date),
    onSuccess: (data) => {
      message.success(data.message || '统计数据已刷新');
      queryClient.invalidateQueries({ queryKey: ['analytics'] });
    },
    onError: () => {
      message.error('刷新统计数据失败');
    },
  });
}

export function useBackfillStatistics() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ startDate, endDate }: { startDate: string; endDate: string }) =>
      analyticsApi.backfillStatistics(startDate, endDate),
    onSuccess: (data) => {
      message.success(data.message || '历史数据回填完成');
      queryClient.invalidateQueries({ queryKey: ['analytics'] });
    },
    onError: () => {
      message.error('历史数据回填失败');
    },
  });
}

// ==================== Financial Reports Hooks ====================

export function useFinancialReports(year?: number, status?: string) {
  return useQuery({
    queryKey: REPORTS_KEYS.list(year, status),
    queryFn: () => analyticsApi.listFinancialReports(year, status),
  });
}

export function useFinancialReport(month: string, enabled = true) {
  return useQuery({
    queryKey: REPORTS_KEYS.detail(month),
    queryFn: () => analyticsApi.getFinancialReport(month),
    enabled: enabled && !!month,
  });
}

export function useGenerateReport() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (month: string) => analyticsApi.generateFinancialReport(month),
    onSuccess: (data) => {
      message.success(data.message || '报表生成成功');
      queryClient.invalidateQueries({ queryKey: ['financial-reports'] });
    },
    onError: () => {
      message.error('报表生成失败');
    },
  });
}

export function useConfirmReport() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (month: string) => analyticsApi.confirmFinancialReport(month),
    onSuccess: () => {
      message.success('报表已确认');
      queryClient.invalidateQueries({ queryKey: ['financial-reports'] });
    },
    onError: () => {
      message.error('报表确认失败');
    },
  });
}

export function useLockReport() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (month: string) => analyticsApi.lockFinancialReport(month),
    onSuccess: () => {
      message.success('报表已锁定');
      queryClient.invalidateQueries({ queryKey: ['financial-reports'] });
    },
    onError: () => {
      message.error('报表锁定失败');
    },
  });
}

export function useUpdateReportNotes() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ month, notes }: { month: string; notes: string }) =>
      analyticsApi.updateReportNotes(month, notes),
    onSuccess: () => {
      message.success('备注已更新');
      queryClient.invalidateQueries({ queryKey: ['financial-reports'] });
    },
    onError: () => {
      message.error('备注更新失败');
    },
  });
}

// ==================== Audit Logs Hooks ====================

export function useAuditLogs(params: AuditLogQueryParams) {
  return useQuery({
    queryKey: AUDIT_KEYS.logs(params),
    queryFn: () => analyticsApi.getAuditLogs(params),
  });
}

export function useAuditLog(id: string, enabled = true) {
  return useQuery({
    queryKey: AUDIT_KEYS.detail(id),
    queryFn: () => analyticsApi.getAuditLog(id),
    enabled: enabled && !!id,
  });
}

export function useAuditActionTypes() {
  return useQuery({
    queryKey: AUDIT_KEYS.actionTypes,
    queryFn: analyticsApi.getActionTypes,
    staleTime: 10 * 60 * 1000, // Cache for 10 minutes
  });
}

export function useAuditEntityTypes() {
  return useQuery({
    queryKey: AUDIT_KEYS.entityTypes,
    queryFn: analyticsApi.getEntityTypes,
    staleTime: 10 * 60 * 1000, // Cache for 10 minutes
  });
}

// ==================== Re-exports for convenience ====================

export type {
  DailyStatisticsDto,
  TrendData,
  FinancialReportDto,
  AuditLogQueryParams,
  PaginatedAuditLogs,
};
