import { useEffect, useState } from 'react';
import { BarChartOutlined, DollarOutlined, GiftOutlined, LineChartOutlined, MessageOutlined, RobotOutlined } from '@ant-design/icons';
import { Card, Empty, App as AntApp, Spin, Tag, Select, Space, Table } from 'antd';
import { Link } from 'react-router-dom';
import { AgentTokenStats, StatsAPI, StatsOverview } from '../api';

type StatsOverviewWithPoints = StatsOverview & {
  totalPoints?: number;
  pointsEarned?: number;
};

let statsOverviewCache:
  | { ts: number; data: StatsOverview | null; inFlight: Promise<StatsOverview> | null }
  | undefined;

const getStatsOverviewCached = () => {
  if (!statsOverviewCache) statsOverviewCache = { ts: 0, data: null, inFlight: null };
  if (statsOverviewCache.inFlight) return statsOverviewCache.inFlight;
  if (statsOverviewCache.data && Date.now() - statsOverviewCache.ts < 5000) return Promise.resolve(statsOverviewCache.data);
  statsOverviewCache.inFlight = StatsAPI.overview()
    .then((res) => {
      statsOverviewCache!.data = res;
      statsOverviewCache!.ts = Date.now();
      return res;
    })
    .finally(() => {
      if (statsOverviewCache) statsOverviewCache.inFlight = null;
    });
  return statsOverviewCache.inFlight;
};

export default function StatsPage() {
  const { message } = AntApp.useApp();
  const [data, setData] = useState<StatsOverviewWithPoints | null>(null);
  const [loading, setLoading] = useState(false);
  const [tokenLoading, setTokenLoading] = useState(false);
  const [tokenData, setTokenData] = useState<AgentTokenStats | null>(null);
  const [tokenAgentId, setTokenAgentId] = useState<string>('');
  const [tokenDays, setTokenDays] = useState<number>(30);
  const [tokenLimit, setTokenLimit] = useState<number>(10);

  useEffect(() => {
    setLoading(true);
    let alive = true;
    getStatsOverviewCached()
      .then((res) => {
        if (!alive) return;
        const enhanced = res as StatsOverviewWithPoints;
        const spent = enhanced.costUSD || 0;
        enhanced.totalPoints = Math.floor(spent * 1000);
        enhanced.pointsEarned = enhanced.totalPoints;
        setData(enhanced);
        if (!tokenAgentId && res.topAgents?.[0]?.id) {
          setTokenAgentId(res.topAgents[0].id);
        }
      })
      .catch((e) => message.error('加载失败：' + (e?.message ?? e)))
      .finally(() => {
        if (alive) setLoading(false);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
    return () => {
      alive = false;
    };
  }, []);

  useEffect(() => {
    if (!tokenAgentId) return;
    setTokenLoading(true);
    StatsAPI.agentTokens(tokenAgentId, { days: tokenDays, limit: tokenLimit })
      .then((res) => {
        setTokenData(res);
      })
      .catch((e) => message.error('Token 统计加载失败：' + (e?.message ?? e)))
      .finally(() => setTokenLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tokenAgentId, tokenDays, tokenLimit]);

  if (loading) return <Spin style={{ marginTop: 80, display: 'block' }} />;
  if (!data) return <Empty description="暂无数据" style={{ marginTop: 80 }} />;

  const maxDaily = Math.max(1, ...data.daily.map((d) => d.total));
  const maxAgent = Math.max(1, ...data.topAgents.map((a) => a.messageCount));
  const last7Days = data.daily.slice(-7).reduce((sum, item) => sum + item.total, 0);
  const avgSessionMessages = data.sessionCount > 0 ? (data.messageCount / data.sessionCount).toFixed(1) : '0.0';
  const formatUSD = (v?: number | null) =>
    `$${Number(v || 0).toLocaleString(undefined, { minimumFractionDigits: 4, maximumFractionDigits: 4 })}`;
  const formatPoints = (v?: number | null) => Number(v || 0).toLocaleString();

  const totalSpentUSD = data.costUSD || 0;
  const totalPoints = Math.floor(totalSpentUSD * 1000);

  return (
    <div className="page-container">
      <div className="stats-page-hero">
        <div className="stats-page-header">
          <div className="stats-page-title-section">
            <div className="stats-page-badge">
              <BarChartOutlined className="stats-page-badge-icon" />
              数据洞察看板
            </div>
            <h1 className="page-title" style={{ marginBottom: 10 }}>调用统计</h1>
            <p className="page-subtitle" style={{ marginTop: 0, fontSize: 15, lineHeight: 1.75 }}>
              不只是查看调用数量，而是帮助你感知哪些智能体正在被频繁使用、最近的消息趋势如何，以及整体会话是否健康增长。
              每消费 1 美元可获得 1000 积分。
            </p>
          </div>
          <div className="stats-page-summary-card">
            <div className="stats-page-summary-label">近 7 天消息总量</div>
            <div className="stats-page-summary-value">{last7Days}</div>
            <div className="stats-page-summary-desc">平均每个会话 {avgSessionMessages} 条消息</div>
          </div>
        </div>

        <div className="stats-page-cards-grid">
          {[
            { icon: <RobotOutlined />, label: '智能体数量', value: data.agentCount, bgColor: 'rgba(8, 145, 178, 0.10)', textColor: 'var(--color-brand)' },
            { icon: <LineChartOutlined />, label: '会话总数', value: data.sessionCount, bgColor: 'rgba(14, 165, 233, 0.10)', textColor: 'var(--color-info)' },
            { icon: <MessageOutlined />, label: '消息总数', value: data.messageCount, bgColor: 'rgba(34, 197, 94, 0.10)', textColor: 'var(--color-success)' }
          ].map((item) => (
            <div key={item.label} className="stats-page-card">
              <div className="stats-page-card-label">
                <span className="stats-page-card-icon" style={{ background: item.bgColor, color: item.textColor }}>
                  {item.icon}
                </span>
                {item.label}
              </div>
              <div className="stats-page-card-value">{item.value}</div>
            </div>
          ))}
        </div>
      </div>

      {/* 积分与消费关联展示 */}
      <div className="points-integration-section">
        <Card
          title="消费与积分"
          className="points-integration-card"
          extra={
            <Tag bordered={false} style={{ borderRadius: 999, background: 'var(--color-brand-soft)', color: 'var(--color-brand)' }}>
              1 USD = 1000 积分
            </Tag>
          }
        >
          <div className="points-integration-row">
            <div className="points-integration-item">
              <div className="points-integration-label">
                <DollarOutlined style={{ color: 'var(--color-warning)' }} />
                累计消费 (USD)
              </div>
              <div className="points-integration-value">{formatUSD(totalSpentUSD)}</div>
              <div className="points-integration-desc">API 调用总费用</div>
            </div>
            <div className="points-integration-item">
              <div className="points-integration-label">
                <GiftOutlined style={{ color: 'var(--color-brand)' }} />
                累计积分
              </div>
              <div className="points-integration-value">{formatPoints(totalPoints)}</div>
              <div className="points-integration-desc">可用于兑换商城商品</div>
            </div>
            <div className="points-integration-item">
              <div className="points-integration-label">
                <BarChartOutlined style={{ color: 'var(--color-success)' }} />
                积分汇率
              </div>
              <div className="points-integration-value">1:1000</div>
              <div className="points-integration-desc">每消费 1 美元获得 1000 积分</div>
            </div>
          </div>
        </Card>
      </div>

      <div className="stats-page-main-grid" style={{ marginTop: 18 }}>
        <Card
          title="最近 30 天消息走势"
          className="stats-page-chart-card"
          extra={<Tag bordered={false} style={{ borderRadius: 999, background: 'var(--color-brand-soft)', color: 'var(--color-brand)' }}>仅统计你的数据</Tag>}
        >
          <div className="stats-page-chart-desc">
            深色柱代表用户消息，浅绿柱代表助手响应，用来快速判断近期对话活跃度。
          </div>
          {data.daily.length === 0 ? (
            <Empty description="近期无对话" />
          ) : (
            <div className="stats-page-chart-container">
              {data.daily.map((d) => {
                const userH = (d.user / maxDaily) * 180;
                const aH = (d.assistant / maxDaily) * 180;
                return (
                  <div
                    key={d.day}
                    className="stats-page-chart-bar-group"
                    title={`${d.day}\n用户 ${d.user} · 助手 ${d.assistant}`}
                  >
                    <div className="stats-page-chart-bars">
                      <div className="stats-page-chart-bar-user" style={{ height: userH }} />
                      <div className="stats-page-chart-bar-assistant" style={{ height: aH }} />
                    </div>
                    <div className="stats-page-chart-label">{d.day.slice(5)}</div>
                  </div>
                );
              })}
            </div>
          )}
          <div className="stats-page-chart-legend">
            <span className="stats-page-chart-legend-item">
              <span className="stats-page-chart-legend-dot" style={{ background: 'var(--color-brand)' }} />
              用户消息
            </span>
            <span className="stats-page-chart-legend-item">
              <span className="stats-page-chart-legend-dot" style={{ background: 'var(--color-success)' }} />
              助手消息
            </span>
          </div>
        </Card>

        <Card title="智能体活跃排行" className="stats-page-chart-card">
          <div className="stats-page-chart-desc">
            哪些智能体正在被频繁使用，一眼就能看出来。
          </div>
          {data.topAgents.length === 0 ? (
            <Empty description="暂无" />
          ) : (
            <div>
              {data.topAgents.map((a, index) => (
                <div key={a.id} className="stats-page-agent-item">
                  <div className="stats-page-agent-header">
                    <div className="stats-page-agent-rank">{index + 1}</div>
                    <Link to={`/agents/${a.id}/chat`} className="stats-page-agent-name">
                      {a.name}
                    </Link>
                    <Tag bordered={false} style={{ background: 'var(--color-surface-2)', color: 'var(--color-text-secondary)', borderRadius: 999, margin: 0 }}>
                      {a.messageCount} 条
                    </Tag>
                  </div>
                  <div className="stats-page-agent-progress">
                    <div className="stats-page-agent-progress-bar" style={{ width: `${(a.messageCount / maxAgent) * 100}%` }} />
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>

      <div className="stats-page-token-section">
        <Card
          title="Token 使用量"
          className="stats-page-chart-card"
          extra={
            <Space size={10} wrap>
              <Select
                size="small"
                value={tokenAgentId || undefined}
                style={{ minWidth: 220 }}
                placeholder="选择智能体"
                onChange={setTokenAgentId}
                options={data.topAgents.map((a) => ({ value: a.id, label: a.name }))}
              />
              <Select
                size="small"
                value={tokenDays}
                style={{ width: 120 }}
                onChange={setTokenDays}
                options={[
                  { value: 7, label: '近 7 天' },
                  { value: 30, label: '近 30 天' },
                  { value: 90, label: '近 90 天' }
                ]}
              />
              <Select
                size="small"
                value={tokenLimit}
                style={{ width: 120 }}
                onChange={setTokenLimit}
                options={[
                  { value: 5, label: 'Top 5' },
                  { value: 10, label: 'Top 10' },
                  { value: 20, label: 'Top 20' }
                ]}
              />
            </Space>
          }
        >
          {tokenLoading ? (
            <Spin style={{ marginTop: 20, display: 'block' }} />
          ) : !tokenAgentId ? (
            <Empty description="暂无可统计的智能体" style={{ marginTop: 20 }} />
          ) : !tokenData ? (
            <Empty description="暂无 Token 统计数据" style={{ marginTop: 20 }} />
          ) : (
            <>
              <div className="stats-page-token-cards-grid">
                {[
                  { label: '总 Token', value: tokenData.totalTokens, color: 'var(--color-brand)' },
                  { label: '输入 Token', value: tokenData.promptTokens, color: 'var(--color-info)' },
                  { label: '输出 Token', value: tokenData.completionTokens, color: 'var(--color-success)' },
                  { label: '费用 (USD)', value: formatUSD(tokenData.costUSD), color: 'var(--color-warning)' }
                ].map((item) => (
                  <div key={item.label} className="stats-page-token-card">
                    <div className="stats-page-token-label">
                      <span className="stats-page-token-dot" style={{ background: item.color }} />
                      {item.label}
                    </div>
                    <div className="stats-page-token-value">
                      {typeof item.value === 'number' ? item.value.toLocaleString() : item.value}
                    </div>
                  </div>
                ))}
              </div>

              <div className="stats-page-token-charts-grid">
                <Card
                  size="small"
                  title="近 N 天趋势（总 Token）"
                  className="stats-page-token-chart-card"
                  extra={
                    <Tag bordered={false} style={{ borderRadius: 999, background: 'var(--color-surface-2)', color: 'var(--color-text-secondary)' }}>
                      days={tokenData.days}
                    </Tag>
                  }
                >
                  {tokenData.daily.length === 0 ? (
                    <Empty description="暂无" />
                  ) : (
                    <div className="stats-page-token-chart-container">
                      {(() => {
                        const maxTokenDaily = Math.max(1, ...tokenData.daily.map((d) => d.totalTokens));
                        return tokenData.daily.map((d) => {
                          const h = (d.totalTokens / maxTokenDaily) * 170;
                          return (
                            <div
                              key={d.day}
                              className="stats-page-chart-bar-group"
                              title={`${d.day}\nCalls ${d.calls}\nTotalTokens ${d.totalTokens}\nCost ${formatUSD(d.costUSD)}`}
                            >
                              <div className="stats-page-token-chart-bar" style={{ height: h }} />
                              <div className="stats-page-chart-label">{d.day.slice(5)}</div>
                            </div>
                          );
                        });
                      })()}
                    </div>
                  )}
                </Card>

                <Card
                  size="small"
                  title="模型消耗排行"
                  className="stats-page-token-chart-card"
                >
                  <Table
                    size="small"
                    pagination={false}
                    rowKey={(r) => `${r.providerKind}:${r.model}`}
                    dataSource={tokenData.byModel || []}
                    columns={[
                      { title: 'Provider', dataIndex: 'providerKind', width: 110 },
                      { title: 'Model', dataIndex: 'model' },
                      { title: 'Calls', dataIndex: 'calls', width: 80 },
                      {
                        title: 'Tokens',
                        dataIndex: 'totalTokens',
                        width: 110,
                        render: (v) => Number(v || 0).toLocaleString()
                      },
                      {
                        title: 'Cost',
                        dataIndex: 'costUSD',
                        width: 110,
                        render: (v) => formatUSD(v)
                      }
                    ]}
                  />
                </Card>
              </div>
            </>
          )}
        </Card>
      </div>
    </div>
  );
}
