'use client'

import { useQuery } from '@tanstack/react-query'
import { apiGet } from '@/lib/api/client'

// Types
export type TimeRange = '7d' | '30d' | '90d'

export interface AnalyticsOverview {
  totalOrders: number
  ordersTrend: number
  activeCustomers: number
  customersTrend: number
  activeSubscriptions: number
  successRate: number
}

export interface DayCount {
  date: string
  count: number
}

export interface DayTokens {
  date: string
  tokens: number
}

export interface OperationTokens {
  operation: string
  tokens: number
}

export interface TopConsumer {
  userId: string
  name: string
  tokens: number
}

export interface RecentFailure {
  orderId: string
  domain: string
  date: string
  reason: string
}

export interface AnalyticsData {
  range: TimeRange
  overview: AnalyticsOverview
  orders: {
    byDay: DayCount[]
    byStatus: Record<string, number>
  }
  customers: {
    growthByDay: DayCount[]
    byPlan: Record<string, number>
    byTier: Record<string, number>
  }
  tokens: {
    usageByDay: DayTokens[]
    byOperation: OperationTokens[]
    topConsumers: TopConsumer[]
  }
  provisioning: {
    successRate: number
    byAutomation: Record<string, number>
    recentFailures: RecentFailure[]
  }
}

// Query keys
export const analyticsKeys = {
  all: ['analytics'] as const,
  dashboard: (range: TimeRange) => [...analyticsKeys.all, 'dashboard', range] as const,
}

// API function
async function getAnalytics(range: TimeRange): Promise<AnalyticsData> {
  return apiGet<AnalyticsData>('/api/v1/admin/analytics', {
    params: { range },
  })
}

// Hook
export function useAnalytics(range: TimeRange = '30d') {
  return useQuery({
    queryKey: analyticsKeys.dashboard(range),
    queryFn: () => getAnalytics(range),
    staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes
  })
}
