'use client'

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

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

  useEffect(() => {
    Promise.all([
      api.get<Integration[]>('/api/apps').catch(() => []),
      api.get<Stats>('/api/analytics/overview').catch(() => null),
    ]).then(([apps, s]) => {
      setIntegrations(apps)
      setStats(s)
      setLoading(false)
    })
  }, [])

  const metrics = [
    { label: 'Total Executions', value: stats?.total_executions ?? 0, icon: Activity, color: 'text-accent-cyan' },
    { label: 'Integrations', value: integrations.length, icon: Plug, color: 'text-accent-green' },
    { label: 'Success Rate', value: `${stats?.success_rate ?? 100}%`, icon: CheckCircle, color: 'text-accent-blue' },
    { label: 'Avg Latency', value: `${stats?.avg_latency_ms ?? 0}ms`, icon: Clock, color: 'text-accent-amber' },
  ]

  return (
    <div className="flex min-h-screen">
      <Sidebar integrationCount={integrations.length} />
      <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">Dashboard</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">{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">Quick Connect</h3>
            {loading ? (
              <p className="text-text-muted text-sm">Loading...</p>
            ) : integrations.length === 0 ? (
              <div className="text-center py-12">
                <p className="text-text-muted">No integrations yet</p>
                <p className="text-text-dim text-sm mt-1">Set COMPOSIO_API_KEY to sync all 1000+ tools</p>
              </div>
            ) : (
              <div className="grid grid-cols-4 gap-4">
                {integrations.slice(0, 8).map((i) => (
                  <div key={i.id} className="bg-bg-secondary border border-border rounded-lg p-4 hover:border-accent-cyan/40 transition-colors">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="w-9 h-9 bg-bg-tertiary rounded-lg flex items-center justify-center overflow-hidden">
                        <img src={i.logo_url} alt={i.name} className="w-5 h-5" onError={(e) => (e.currentTarget.style.display = 'none')} />
                      </div>
                      <div>
                        <p className="text-sm font-medium">{i.name}</p>
                        <p className="text-[11px] text-text-muted">{i.category}</p>
                      </div>
                    </div>
                    <div className="flex items-center justify-between pt-3 border-t border-border">
                      <span className="text-[11px] text-text-muted">{i.tool_count} tools</span>
                      <span className={`text-[11px] px-2 py-0.5 rounded ${i.auth_type === 'oauth2' ? 'bg-accent-cyan/10 text-accent-cyanLight' : 'bg-accent-green/10 text-accent-green'}`}>
                        {i.auth_type}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  )
}