'use client'

import { useEffect, useState } from 'react'
import { Sidebar } from '@/components/sidebar'
import { api, type Stats } from '@/lib/api'
import { Activity, CheckCircle, XCircle, Clock } from 'lucide-react'

export default function AnalyticsPage() {
  const [stats, setStats] = useState<Stats | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.get<Stats>('/api/analytics/overview')
      .then((data) => { setStats(data); setLoading(false) })
      .catch(() => setLoading(false))
  }, [])

  const metrics = [
    { label: 'Executions', value: stats?.total_executions ?? 0, icon: Activity, color: 'text-accent-cyan' },
    { label: 'Successful', value: stats?.successful ?? 0, icon: CheckCircle, color: 'text-accent-green' },
    { label: 'Failed', value: stats?.failed ?? 0, icon: XCircle, color: 'text-accent-red' },
    { label: 'Avg Latency', value: `${stats?.avg_latency_ms ?? 0}ms`, icon: Clock, color: 'text-accent-amber' },
  ]

  return (
    <div className="flex min-h-screen">
      <Sidebar />
      <main className="flex-1 flex flex-col">
        <header className="h-14 bg-bg-secondary border-b border-border flex items-center px-6">
          <h1 className="text-base font-medium">Analytics</h1>
        </header>
        <div className="flex-1 p-6 space-y-6 overflow-auto">
          <div className="grid grid-cols-4 gap-4">
            {metrics.map((m) => (
              <div key={m.label} className="bg-bg-tertiary border border-border rounded-xl p-5">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-text-muted">{m.label}</p>
                    <p className={`text-2xl font-bold mt-1 ${m.color}`}>{loading ? '...' : m.value}</p>
                  </div>
                  <m.icon className={`w-5 h-5 ${m.color}`} />
                </div>
              </div>
            ))}
          </div>
          <div className="bg-bg-tertiary border border-border rounded-xl p-6">
            <h3 className="text-sm font-medium mb-4">Success Rate</h3>
            <div className="flex items-center gap-4">
              <div className="flex-1 h-3 bg-bg-secondary rounded-full overflow-hidden">
                <div className="h-full bg-accent-green rounded-full transition-all" style={{ width: `${stats?.success_rate ?? 100}%` }} />
              </div>
              <span className="text-sm font-medium">{stats?.success_rate ?? 100}%</span>
            </div>
          </div>
        </div>
      </main>
    </div>
  )
}