import { AreaChart, Area, XAxis, YAxis, CartesianGrid, ResponsiveContainer, Tooltip } from 'recharts'
import { Card } from 'tdesign-react'
import type { UsageStats } from '@/types'

interface UsageChartProps {
  stats: UsageStats[]
  isLoading?: boolean
}

export function UsageChart({ stats, isLoading }: UsageChartProps) {
  const chartData = Object.entries(
    stats.reduce<Record<string, number>>((acc, s) => {
      acc[s.date] = (acc[s.date] || 0) + s.requestCount
      return acc
    }, {})
  )
    .map(([date, requestCount]) => ({ date, requestCount }))
    .sort((a, b) => a.date.localeCompare(b.date))

  return (
    <Card title='请求趋势' headerBordered hoverShadow loading={isLoading} style={{ marginBottom: 16 }}>
      {chartData.length > 0 ? (
        <ResponsiveContainer width='100%' height={300}>
          <AreaChart data={chartData}>
            <defs>
              <linearGradient id='requestGradient' x1='0' y1='0' x2='0' y2='1'>
                <stop offset='0%' stopColor='#0052D9' stopOpacity={0.4} />
                <stop offset='100%' stopColor='#0052D9' stopOpacity={0} />
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray='3 3' stroke='#e8e8e8' />
            <XAxis dataKey='date' />
            <YAxis />
            <Tooltip />
            <Area
              type='monotone'
              dataKey='requestCount'
              stroke='#0052D9'
              strokeWidth={2}
              fill='url(#requestGradient)'
            />
          </AreaChart>
        </ResponsiveContainer>
      ) : (
        <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--td-text-color-placeholder)' }}>
          暂无数据
        </div>
      )}
    </Card>
  )
}
