import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Upload, RefreshCw, Settings } from 'lucide-react'
import { PoolStatus, RecentRecords } from '../components/dashboard'
import { Card, CardHeader, CardTitle, CardContent, Button } from '../components/common'
import { useS2AApi } from '../hooks/useS2AApi'
import { useRecords } from '../hooks/useRecords'
import { useConfig } from '../hooks/useConfig'
import type { DashboardStats } from '../types'
import { formatNumber, formatCurrency } from '../utils/format'

export default function Dashboard() {
  const { getDashboardStats, loading, error, isConnected } = useS2AApi()
  const { records } = useRecords()
  const { config } = useConfig()
  const [stats, setStats] = useState<DashboardStats | null>(null)
  const [refreshing, setRefreshing] = useState(false)

  const fetchStats = async () => {
    if (!isConnected) return
    setRefreshing(true)
    const data = await getDashboardStats()
    if (data) {
      setStats(data)
    }
    setRefreshing(false)
  }

  useEffect(() => {
    fetchStats()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isConnected])

  const hasConfig = config.s2a.apiBase && config.s2a.adminKey

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100">仪表盘</h1>
          <p className="text-sm text-slate-500 dark:text-slate-400">号池状态概览</p>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={fetchStats}
            disabled={!isConnected || refreshing}
            icon={<RefreshCw className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`} />}
          >
            刷新
          </Button>
          <Link to="/upload">
            <Button size="sm" icon={<Upload className="h-4 w-4" />}>
              上传入库
            </Button>
          </Link>
        </div>
      </div>

      {/* Connection warning */}
      {!hasConfig && (
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-xl p-4">
          <div className="flex items-start gap-3">
            <Settings className="h-5 w-5 text-yellow-600 dark:text-yellow-400 mt-0.5" />
            <div>
              <p className="font-medium text-yellow-800 dark:text-yellow-200">请先配置 S2A 连接</p>
              <p className="mt-1 text-sm text-yellow-700 dark:text-yellow-300">
                前往系统配置页面设置 S2A API 地址和管理密钥
              </p>
              <Link to="/config" className="mt-3 inline-block">
                <Button size="sm" variant="outline">
                  前往配置
                </Button>
              </Link>
            </div>
          </div>
        </div>
      )}

      {/* Pool Status */}
      <PoolStatus stats={stats} loading={loading || refreshing} error={error} />

      {/* Stats Summary */}
      {stats && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card hoverable>
            <CardHeader>
              <CardTitle>今日统计</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-slate-500 dark:text-slate-400">请求数</p>
                  <p className="text-xl font-bold text-slate-900 dark:text-slate-100">
                    {formatNumber(stats.today_requests)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-slate-500 dark:text-slate-400">Token 消耗</p>
                  <p className="text-xl font-bold text-slate-900 dark:text-slate-100">
                    {formatNumber(stats.today_tokens)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-slate-500 dark:text-slate-400">费用</p>
                  <p className="text-xl font-bold text-slate-900 dark:text-slate-100">
                    {formatCurrency(stats.today_cost)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-slate-500 dark:text-slate-400">TPM</p>
                  <p className="text-xl font-bold text-slate-900 dark:text-slate-100">
                    {formatNumber(stats.tpm)}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card hoverable>
            <CardHeader>
              <CardTitle>累计统计</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-slate-500 dark:text-slate-400">总请求数</p>
                  <p className="text-xl font-bold text-slate-900 dark:text-slate-100">
                    {formatNumber(stats.total_requests)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-slate-500 dark:text-slate-400">总 Token</p>
                  <p className="text-xl font-bold text-slate-900 dark:text-slate-100">
                    {formatNumber(stats.total_tokens)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-slate-500 dark:text-slate-400">总费用</p>
                  <p className="text-xl font-bold text-slate-900 dark:text-slate-100">
                    {formatCurrency(stats.total_cost)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-slate-500 dark:text-slate-400">过载账号</p>
                  <p className="text-xl font-bold text-slate-900 dark:text-slate-100">
                    {stats.overload_accounts}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Recent Records */}
      <RecentRecords records={records} loading={loading} />
    </div>
  )
}
