import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '@/api/client'

export interface ConversationsSummary {
  total_conversations: number
}

/**
 * Usage page: only track total conversations.
 */
export function useConversationsCount(days: number = 30) {
  return useQuery({
    queryKey: ['usage', 'conversations', days],
    queryFn: async () => {
      const response = await apiClient.get<{ data: { summary: ConversationsSummary } }>(`usage/conversations?days=${days}`)
      return response.data.summary
    },
    staleTime: 60 * 1000, // 1 minute
  })
}

// Week 30: CreditBucket now uses number to support decimal values (formatted to 2 decimal places in UI)
export type CreditBucket = { total: number; used: number; remaining: number }

export type CreditsStatus = {
  site_id: string
  site_status?: 'active' | 'blocked' | 'disabled'
  allowed: boolean
  // Week 30: Unified BoostCoin wallet (single coin type across all operations).
  // Values are decimal numbers representing fractional credits.
  boost_credits: CreditBucket
  // Legacy buckets for backward compatibility (kept during migration)
  credits: {
    free: CreditBucket
    subscription: CreditBucket & { renew_at: string | null; status: 'none' | 'active' | 'paused' | 'cancelled' }
    purchased: CreditBucket
  }
  active_model:
    | { provider: 'google'; model: string; credit_type: 'free'; config: Record<string, unknown> }
    | { provider: 'openai'; model: string; credit_type: 'free' | 'subscription' | 'purchased'; config: Record<string, unknown> }
    | { provider: 'none'; model: 'none'; credit_type: 'none'; config: Record<string, unknown> }
}

export type PricingPackage = {
  id: string
  name: string
  price: number
  credits: number
  cost_per_conversation: number
  popular: boolean
}

// Week 30: indexing_packages removed - all credits are now unified BoostCoin
export type PricingCatalog = {
  currency: string
  packages: PricingPackage[]
  subscriptions: Array<{ id: string; name: string; price: number; allowance: number; popular: boolean }>
  /** @deprecated Week 30 - Indexing packages removed. Always empty. */
  indexing_packages?: Array<{ id: string; name: string; price: number; credits: number; popular: boolean }>
}

export type UsageHistoryDay = {
  date: string
  consumed: number
  operations: number
}

export type UsageHistoryCategory = {
  category: string
  consumed: number
  operations: number
}

export type UsageHistory = {
  days: number
  since: string
  daily: UsageHistoryDay[]
  categories: UsageHistoryCategory[]
  totals: { consumed: number; operations: number }
}

export function useCreditsUsageHistory(days: number = 30) {
  return useQuery({
    queryKey: ['credits', 'usage-history', days],
    queryFn: async () => {
      const response = await apiClient.get<{ data: UsageHistory }>(`credits/usage-history?days=${days}`)
      return response.data
    },
    staleTime: 60 * 1000, // 1 minute
  })
}

export function useCreditsStatus() {
  return useQuery({
    queryKey: ['week26', 'credits', 'status'],
    queryFn: async () => {
      const response = await apiClient.get<{ data: CreditsStatus }>('credits/status')
      return response.data
    },
    staleTime: 10 * 1000, // keep fresh; status changes quickly after consume/purchase
  })
}

export function usePricingCatalog() {
  return useQuery({
    queryKey: ['week26', 'pricing', 'catalog'],
    queryFn: async () => {
      const response = await apiClient.get<{ data: PricingCatalog }>('pricing/catalog')
      return response.data
    },
    staleTime: 60 * 60 * 1000, // 1 hour
  })
}

export function useCreatePurchaseOrder() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async ({ package_id }: { package_id: string }) => {
      const response = await apiClient.post<{ data: { approval_url: string; order_id: string } }>('purchases/create-order', {
        package_id,
      })
      return response.data
    },
    onSuccess: async () => {
      // After redirect+webhook, credits will change; user may come back and refresh.
      await queryClient.invalidateQueries({ queryKey: ['week26', 'credits'] })
      await queryClient.invalidateQueries({ queryKey: ['week26', 'pricing'] })
    },
  })
}

export function useCreateSubscription() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async ({ package_id }: { package_id: string }) => {
      const response = await apiClient.post<{ data: { approval_url: string; subscription_id: string } }>('subscriptions/create', {
        package_id,
      })
      return response.data
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ['week26', 'credits'] })
      await queryClient.invalidateQueries({ queryKey: ['week26', 'pricing'] })
    },
  })
}

export function useCapturePurchaseOrder() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async ({ order_id }: { order_id: string }) => {
      const response = await apiClient.post<{ data: any }>('purchases/capture-order', { order_id })
      return response.data
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ['week26', 'credits'] })
    },
  })
}

export function useMigrateNow() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async () => {
      const response = await apiClient.post<{ data: any }>('migration/migrate-now', {})
      return response.data
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ['week26', 'credits'] })
    },
  })
}

