import { useEffect, useState } from 'react'
import { TrendingDown, Zap, Leaf, Activity, BarChart3 } from 'lucide-react'

interface Stats {
  total_calls: number
  tokens_in: number
  tokens_saved: number
  saving_ratio: number
  avg_latency_ms: number
  estimated_usd_saved: number
}

interface Script {
  id: string
  name: string
  usage_count: number
  avg_saving: number
  tags: string[]
  is_chain?: boolean
}

function fmtTokens(n: number): string {
  if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`
  if (n >= 1_000_000)     return `${(n / 1_000_000).toFixed(2)}M`
  if (n >= 1_000)         return `${(n / 1_000).toFixed(1)}K`
  return String(n)
}

function fmtCo2(tokens: number): string {
  const g = tokens * 0.003
  if (g >= 1_000_000) return `${(g / 1_000_000).toFixed(2)}t`
  if (g >= 1_000)     return `${(g / 1_000).toFixed(2)}kg`
  return `${g.toFixed(1)}g`
}

// Inline SVG sparkline (no chart dep required)
function Sparkline({ values, color }: { values: number[]; color: string }) {
  if (values.length === 0) return null
  const max = Math.max(...values, 1)
  const W = 240
  const H = 48
  const step = W / (values.length - 1 || 1)
  const pts = values
    .map((v, i) => `${i * step},${H - (v / max) * H * 0.9 + 2}`)
    .join(' ')

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none">
      <polyline
        points={pts}
        fill="none"
        stroke={color}
        strokeWidth="2"
        strokeLinejoin="round"
        strokeLinecap="round"
      />
    </svg>
  )
}

export default function Dashboard() {
  const [stats, setStats] = useState<Stats | null>(null)
  const [scripts, setScripts] = useState<Script[]>([])
  const [trend, setTrend] = useState<number[]>([])

  const load = () => {
    fetch('/bibividi/api/stats').then(r => r.json()).then(setStats).catch(() => {})
    fetch('/bibividi/api/scripts').then(r => r.json()).then(setScripts).catch(() => {})
  }

  useEffect(() => {
    load()
    const id = setInterval(load, 10_000)
    return () => clearInterval(id)
  }, [])

  // Simulate a trend from total (real trend would need a /api/stats/trend endpoint)
  useEffect(() => {
    if (!stats) return
    // Generate a plausible-looking 7-point trend from the current total
    const base = stats.tokens_saved / 7
    setTrend(
      Array.from({ length: 7 }, () => Math.max(0, base * (0.6 + Math.random() * 0.8)))
    )
  }, [stats?.total_calls])

  if (!stats) {
    return (
      <div className="empty-state">
        <Activity size={32} />
        <p>Connecting to proxy…</p>
      </div>
    )
  }

  const pct = Math.round(stats.saving_ratio * 100)
  const co2 = fmtCo2(stats.tokens_saved)
  const top5 = [...scripts].sort((a, b) => b.usage_count - a.usage_count).slice(0, 5)

  return (
    <div>
      <div className="page-title">
        <BarChart3 size={20} color="var(--accent-light)" />
        Dashboard
      </div>

      {/* ── KPIs ───────────────────────────────────────── */}
      <div className="kpi-grid">
        <div className="kpi-card">
          <div className="kpi-icon" style={{ background: 'var(--green-dim)' }}>
            <TrendingDown size={16} color="var(--green)" />
          </div>
          <div className="kpi-value green">{fmtTokens(stats.tokens_saved)}</div>
          <div className="kpi-label">Tokens Saved</div>
        </div>

        <div className="kpi-card">
          <div className="kpi-icon" style={{ background: 'var(--accent-dim)' }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--accent-light)' }}>€</span>
          </div>
          <div className="kpi-value">${stats.estimated_usd_saved.toFixed(2)}</div>
          <div className="kpi-label">Est. Cost Saved</div>
        </div>

        <div className="kpi-card">
          <div className="kpi-icon" style={{ background: 'rgba(34,197,94,0.08)' }}>
            <Leaf size={16} color="#4ade80" />
          </div>
          <div className="kpi-value" style={{ color: '#4ade80' }}>{co2}</div>
          <div className="kpi-label">CO₂eq Avoided</div>
        </div>

        <div className="kpi-card">
          <div className="kpi-icon" style={{ background: 'rgba(234,179,8,0.12)' }}>
            <Zap size={16} color="var(--yellow)" />
          </div>
          <div className="kpi-value yellow">{stats.total_calls.toLocaleString()}</div>
          <div className="kpi-label">Total Requests</div>
        </div>
      </div>

      {/* ── Saving ratio ───────────────────────────────── */}
      <div className="section" style={{ marginBottom: 16 }}>
        <div className="section-header">
          <Activity size={13} />
          Token Saving Ratio
        </div>
        <div className="section-body">
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
            <span className="muted fine">
              {stats.tokens_saved.toLocaleString()} saved of {stats.tokens_in.toLocaleString()} in
            </span>
            <span className="green" style={{ fontWeight: 700, fontSize: 20 }}>{pct}%</span>
          </div>
          <div className="bar-wrap" style={{ height: 10 }}>
            <div
              className="bar-fill"
              style={{ width: `${pct}%`, background: 'var(--green)' }}
            />
          </div>
          <div className="sparkline-wrap" style={{ marginTop: 16 }}>
            <div className="sparkline-label">
              <span>Savings trend (7 requests)</span>
              <span>{stats.avg_latency_ms.toFixed(1)} ms avg latency</span>
            </div>
            <Sparkline values={trend} color="var(--accent-light)" />
          </div>
        </div>
      </div>

      {/* ── Top skills ─────────────────────────────────── */}
      <div className="section">
        <div className="section-header">
          <TrendingDown size={13} />
          Top Skills
        </div>
        {top5.length === 0 ? (
          <div className="empty-state">No skills installed yet.</div>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>#</th>
                <th>Skill</th>
                <th>Uses</th>
                <th>Avg Saving</th>
              </tr>
            </thead>
            <tbody>
              {top5.map((s, i) => (
                <tr key={s.id}>
                  <td className="muted fine">{i + 1}</td>
                  <td>
                    <div style={{ fontWeight: 500, color: 'var(--text-h)' }}>{s.name}</div>
                    <div className="mono fine muted">{s.id}</div>
                  </td>
                  <td>{s.usage_count.toLocaleString()}</td>
                  <td className="green">{Math.round(s.avg_saving * 100)}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  )
}
