bookwiz.io / app / dashboard / usage / page.tsx
page.tsx
Raw
'use client'

import { useState, useEffect } from 'react'
import { ChartBarIcon, SparklesIcon, CpuChipIcon, CalendarIcon } from '@heroicons/react/24/outline'
import { useAuth } from '@/components/AuthProvider'
import { useUsageStats } from '@/lib/hooks/useUsageStats'
import DashboardLayout from '@/components/dashboard/DashboardLayout'
import UsageChart from '@/components/UsageChart'

interface MonthlyUsageData {
  model_name: string
  model_tier: 'smart' | 'fast'
  model_provider: string
  request_type: string
  usage_count: number
  total_tokens: number
  total_cost: number
}

export default function DashboardUsagePage() {
  const { user } = useAuth()
  const { usageStats, loading: statsLoading, getSmartUsagePercentage, getFastUsagePercentage } = useUsageStats()
  const [monthlyUsage, setMonthlyUsage] = useState<MonthlyUsageData[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedMonth, setSelectedMonth] = useState(new Date())

  useEffect(() => {
    if (user?.id) {
      fetchMonthlyUsage()
    }
  }, [user?.id, selectedMonth])

  const fetchMonthlyUsage = async () => {
    if (!user?.id) return

    try {
      setLoading(true)
      const response = await fetch(`/api/usage/monthly?userId=${user.id}&month=${selectedMonth.toISOString()}`)
      if (response.ok) {
        const data = await response.json()
        setMonthlyUsage(data || [])
      }
    } catch (error) {
      console.error('Error fetching monthly usage:', error)
    } finally {
      setLoading(false)
    }
  }

  const getMonthOptions = () => {
    const options = []
    const currentDate = new Date()
    
    // Get last 6 months
    for (let i = 0; i < 6; i++) {
      const date = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1)
      options.push({
        value: date,
        label: date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })
      })
    }
    
    return options
  }

  const getTotalUsageByTier = (tier: 'smart' | 'fast') => {
    return monthlyUsage
      .filter(item => item.model_tier === tier)
      .reduce((sum, item) => sum + item.usage_count, 0)
  }

  const getTotalTokensByTier = (tier: 'smart' | 'fast') => {
    return monthlyUsage
      .filter(item => item.model_tier === tier)
      .reduce((sum, item) => sum + item.total_tokens, 0)
  }

  const getModelBreakdown = () => {
    const modelMap = new Map()
    
    monthlyUsage.forEach(item => {
      const key = `${item.model_name}-${item.model_tier}`
      if (modelMap.has(key)) {
        const existing = modelMap.get(key)
        existing.usage_count += item.usage_count
        existing.total_tokens += item.total_tokens
        existing.total_cost += item.total_cost
      } else {
        modelMap.set(key, { ...item })
      }
    })
    
    return Array.from(modelMap.values()).sort((a, b) => b.usage_count - a.usage_count)
  }

  const formatNumber = (num: number) => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + 'M'
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'K'
    }
    return num.toString()
  }

  return (
    <DashboardLayout 
      title="Usage Analytics" 
      subtitle="Track your AI model usage and consumption patterns"
    >
      <div className="space-y-8">
        {/* Current Period Overview */}
        <div className="space-y-4">
          <h2 className="text-xl font-bold text-white">Current Billing Period</h2>
          <UsageChart />
        </div>
      </div>
    </DashboardLayout>
  )
}