import { Button, Card, Col, Empty, Progress, Row, Spin, Tag, Tooltip } from 'antd'
import { Line } from '@ant-design/charts'
import { useNavigate } from 'react-router-dom'
import {
  AimOutlined,
  BarChartOutlined,
  CheckCircleOutlined,
  CloudServerOutlined,
  FileTextOutlined,
  PlayCircleOutlined,
  PlusOutlined,
  ReloadOutlined,
  RobotOutlined,
  SyncOutlined,
} from '@ant-design/icons'
import { statsApi, type DashboardStats, type Run, type TrendPoint } from '../api'
import PageWrapper from '../components/PageWrapper'
import StatCard from '../components/StatCard'
import { useResource } from '../hooks/useResource'
import { colors, statusColors, statusLabels, triggerColors, triggerLabels } from '../tokens'
import { formatDateTime } from '../utils/date'
import { passRateColor } from '../utils/colors'

interface DashboardData {
  stats: DashboardStats
  trend: TrendPoint[]
}

export default function HomePage() {
  const navigate = useNavigate()
  const { data, loading, reload } = useResource<DashboardData>(
    async () => {
      const [d, t] = await Promise.all([statsApi.dashboard(), statsApi.trend(30)])
      return { stats: d.data, trend: t.data }
    },
    { tabPath: '/' },
  )
  const stats = data?.stats ?? null
  const trend = data?.trend ?? []

  const passRate = stats?.overall_pass_rate ?? null

  const trendConfig = {
    data: trend,
    xField: 'date',
    yField: 'pass_rate',
    smooth: true,
    height: 240,
    yAxis: { label: { formatter: (v: string) => `${v}%` }, min: 0, max: 100 },
    point: { size: 3 },
    color: '#1677ff',
    tooltip: {
      formatter: (datum: TrendPoint) => ({
        name: '通过率',
        value: `${datum.pass_rate}%（${datum.run_count ?? '-'} 次执行）`,
      }),
    },
  }

  return (
    <PageWrapper
      title="仪表盘"
      description="评测平台概览与统计数据"
      inline
      fullHeight
      extra={
        <Tooltip title="刷新数据">
          <Button size="middle" icon={<ReloadOutlined />} onClick={() => reload()} />
        </Tooltip>
      }
    >
      <div style={{ height: '100%', overflowY: 'auto', padding: '0 16px 16px' }}>
        <Spin spinning={loading}>
          {/* 指标卡行 */}
          <Row gutter={[16, 16]}>
            <Col xs={12} sm={8} xl={4}>
              <StatCard icon={<AimOutlined />} color="blue" title="评测对象" value={stats?.targets_count ?? 0} />
            </Col>
            <Col xs={12} sm={8} xl={4}>
              <StatCard icon={<FileTextOutlined />} color="green" title="评测场景" value={stats?.scenarios_count ?? 0} />
            </Col>
            <Col xs={12} sm={8} xl={4}>
              <StatCard icon={<CloudServerOutlined />} color="purple" title="模型配置" value={stats?.model_configs_count ?? 0} />
            </Col>
            <Col xs={12} sm={8} xl={4}>
              <StatCard
                icon={<PlayCircleOutlined />} color="orange" title="累计执行"
                value={stats?.runs_count ?? 0}
                subText={stats?.today_runs ? `今日 ${stats.today_runs} 次` : undefined}
              />
            </Col>
            <Col xs={12} sm={8} xl={4}>
              <StatCard
                icon={<SyncOutlined spin={(stats?.running_count ?? 0) > 0} />}
                color={(stats?.running_count ?? 0) > 0 ? 'blue' : 'green'}
                title="运行中"
                value={stats?.running_count ?? 0}
                valueStyle={(stats?.running_count ?? 0) > 0 ? { color: '#1677ff' } : undefined}
              />
            </Col>
            <Col xs={12} sm={8} xl={4}>
              <StatCard
                icon={<CheckCircleOutlined />}
                color={passRate != null && passRate >= 0.8 ? 'green' : 'red'}
                title="平均通过率"
                value={passRate != null ? passRate * 100 : '-'}
                suffix={passRate != null ? '%' : undefined}
                precision={1}
                valueStyle={{ color: passRate != null ? passRateColor(passRate) : colors.textMuted }}
              />
            </Col>
          </Row>

          {/* 图表行 */}
          <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
            <Col xs={24} lg={14}>
              <Card title="通过率趋势（近 30 天）" size="small" styles={{ body: { minHeight: 260 } }}>
                {trend.length > 0 ? (
                  <Line {...trendConfig} />
                ) : (
                  <Empty style={{ paddingTop: 60 }} description="暂无趋势数据" />
                )}
              </Card>
            </Col>
            <Col xs={24} lg={10}>
              <Card title="场景表现" size="small" styles={{ body: { minHeight: 260, overflowY: 'auto', maxHeight: 300 } }}>
                {stats?.scenario_stats.length ? stats.scenario_stats.map((s) => (
                  <div
                    key={s.scenario_id}
                    onClick={() => navigate('/reports')}
                    style={{ padding: '8px 4px', cursor: 'pointer', borderBottom: `1px solid ${colors.border}` }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                      <span style={{ fontSize: 13, fontWeight: 500 }}>{s.scenario_name}</span>
                      <span style={{ fontSize: 12, color: colors.textSecondary }}>
                        {s.run_count} 次 · {s.last_run_at ? formatDateTime(s.last_run_at) : '-'}
                      </span>
                    </div>
                    <Progress
                      percent={s.avg_pass_rate != null ? Math.round(s.avg_pass_rate * 100) : 0}
                      size="small"
                      strokeColor={s.avg_pass_rate != null ? passRateColor(s.avg_pass_rate) : colors.textMuted}
                    />
                  </div>
                )) : <Empty style={{ paddingTop: 60 }} description="暂无已完成的评测" />}
              </Card>
            </Col>
          </Row>

          {/* 动态行 */}
          <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
            <Col xs={24} lg={14}>
              <Card title="最近评测记录" size="small">
                {stats?.recent_runs.length ? stats.recent_runs.map((r) => (
                  <RecentRunRow key={r.id} run={r} onOpen={() => navigate(r.status === 'completed' ? `/reports?run=${r.id}` : '/runs')} />
                )) : <Empty description="还没有评测记录" />}
              </Card>
            </Col>
            <Col xs={24} lg={10}>
              <Card title="快捷操作" size="small" style={{ marginBottom: 16 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
                  <Button icon={<PlayCircleOutlined />} onClick={() => navigate('/runs')}>发起评测</Button>
                  <Button icon={<PlusOutlined />} onClick={() => navigate('/scenarios')}>新建场景</Button>
                  <Button icon={<RobotOutlined />} onClick={() => navigate('/openclaw')}>AI 助手</Button>
                </div>
              </Card>
              <Card title="触发来源分布" size="small">
                {stats && Object.keys(stats.trigger_breakdown).length > 0 ? (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {(Object.entries(stats.trigger_breakdown) as Array<[string, number]>).map(([k, count]) => (
                      <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Tag color={triggerColors[k] ?? 'default'} style={{ margin: 0, width: 72, textAlign: 'center' }}>
                          {triggerLabels[k] ?? k}
                        </Tag>
                        <Progress
                          percent={stats.runs_count ? Math.round((count / stats.runs_count) * 100) : 0}
                          size="small"
                          style={{ flex: 1, margin: 0 }}
                        />
                        <span style={{ fontSize: 12, color: colors.textSecondary, width: 40, textAlign: 'right' }}>{count} 次</span>
                      </div>
                    ))}
                  </div>
                ) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />}
              </Card>
            </Col>
          </Row>
        </Spin>
      </div>
    </PageWrapper>
  )
}

function RecentRunRow({ run, onOpen }: { run: Run; onOpen: () => void }) {
  const rate = run.summary?.pass_rate
  const dotColor = statusColors[run.status] ?? colors.textMuted
  const trigger = run.triggered_by ?? 'manual'
  return (
    <div
      className="run-row"
      onClick={onOpen}
      style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '8px 4px', cursor: 'pointer',
        borderBottom: `1px solid ${colors.border}`,
      }}
    >
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: dotColor, flexShrink: 0 }} />
      <div style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: 13 }}>
        <span style={{ fontWeight: 500 }}>{run.scenario_name || run.scenario_id.slice(0, 8)}</span>
        <span style={{ color: colors.textMuted }}> · {run.target_name || run.target_id.slice(0, 8)}</span>
      </div>
      <Tag color={triggerColors[trigger] ?? 'default'} style={{ margin: 0, fontSize: 10, lineHeight: '16px', padding: '0 4px' }}>
        {triggerLabels[trigger] ?? trigger}
      </Tag>
      {run.scenario_version != null && (
        <Tag style={{ margin: 0, fontSize: 10, lineHeight: '16px', padding: '0 4px' }}>
          v{run.scenario_version}
        </Tag>
      )}
      <span style={{ fontSize: 12, color: dotColor, width: 48, flexShrink: 0 }}>{statusLabels[run.status] ?? run.status}</span>
      <span style={{
        fontSize: 12, fontWeight: 600, width: 44, textAlign: 'right', flexShrink: 0,
        color: rate != null ? passRateColor(rate) : colors.textMuted,
      }}>
        {rate != null ? `${Math.round(rate * 100)}%` : '-'}
      </span>
      <span style={{ fontSize: 12, color: colors.textMuted, width: 130, textAlign: 'right', flexShrink: 0 }}>
        {run.started_at ? formatDateTime(run.started_at) : '-'}
      </span>
      <BarChartOutlined style={{ color: colors.textMuted }} />
    </div>
  )
}
