import { useSystemOverview, useBrainStats } from '../hooks/usePulseAPI'
import { useState, useMemo } from 'react'
import {
  BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell,
  RadialBarChart, RadialBar, PolarAngleAxis,
  AreaChart, Area,
} from 'recharts'

/* ── tiny stat card with optional trend ── */
function StatCard({
  label,
  value,
  icon,
  trend,
}: {
  label: string
  value: string | number
  icon?: string
  trend?: 'up' | 'down' | 'flat'
}) {
  const trendColor =
    trend === 'up' ? 'text-emerald-400' : trend === 'down' ? 'text-rose-400' : 'text-slate-500'
  const trendIcon =
    trend === 'up' ? '\u2191' : trend === 'down' ? '\u2193' : '\u2014'

  return (
    <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-4">
      <p className="text-xs font-medium text-slate-400 uppercase tracking-wider mb-1">
        {label}
      </p>
      <div className="flex items-end justify-between">
        <p className="text-2xl font-bold text-slate-100">{value}</p>
        <div className="flex items-center gap-1">
          {trend && (
            <span className={`text-xs font-medium ${trendColor}`}>{trendIcon}</span>
          )}
          {icon && <span className="text-lg">{icon}</span>}
        </div>
      </div>
    </div>
  )
}

/* ── bar chart colors ── */
const BAR_COLORS = [
  '#38bdf8', // sky-400
  '#f59e0b', // amber-500
  '#a78bfa', // violet-400
  '#34d399', // emerald-400
  '#fb7185', // rose-400
  '#60a5fa', // blue-400
  '#818cf8', // indigo-400
  '#f472b6', // pink-400
  '#2dd4bf', // teal-400
  '#fbbf24', // amber-400
]

/* ── custom tooltip ── */
function ChartTooltip({ active, payload }: any) {
  if (!active || !payload?.length) return null
  const d = payload[0].payload
  return (
    <div className="bg-slate-900/90 backdrop-blur-sm border border-slate-700 rounded-lg px-3 py-2 text-xs">
      <p className="text-slate-300 font-medium">{d.name}</p>
      <p className="text-sky-400 font-bold">{d.count ?? d.value}</p>
    </div>
  )
}

/* ── health score calculator ── */
function computeHealthScore(brain: any): number {
  const lessons = brain.lessons || 0
  const failures = brain.failures || 0
  const patterns = brain.patterns || 0
  const wants = brain.wants || 0
  const evidence = brain.evidence || 0
  const rate = brain.extraction_rate || 0
  const nodes = brain.graph_nodes || 0

  // Weighted scoring: lessons + patterns high value, failures moderate, rate important
  let score = 0
  score += Math.min(lessons / 50, 1) * 20      // up to 20 pts for 50+ lessons
  score += Math.min(patterns / 20, 1) * 15     // up to 15 pts for 20+ patterns
  score += Math.min(wants / 20, 1) * 10        // up to 10 pts for 20+ wants
  score += Math.min(evidence / 100, 1) * 15    // up to 15 pts for 100+ evidence
  score += Math.min(rate / 40, 1) * 20         // up to 20 pts for 40%+ extraction rate
  score += Math.min(nodes / 100, 1) * 10       // up to 10 pts for 100+ graph nodes
  score += Math.min(failures / 10, 1) * 10     // up to 10 pts for 10+ failures (learning from mistakes)
  return Math.min(Math.round(score), 100)
}

function healthLabel(score: number): string {
  if (score >= 80) return 'Excellent'
  if (score >= 60) return 'Good'
  if (score >= 40) return 'Developing'
  if (score >= 20) return 'Nascent'
  return 'Initializing'
}

function healthColor(score: number): string {
  if (score >= 80) return '#34d399' // emerald
  if (score >= 60) return '#38bdf8' // sky
  if (score >= 40) return '#fbbf24' // amber
  return '#fb7185'                  // rose
}

export default function BrainStats() {
  const { data: systemData, loading } = useSystemOverview()
  const [view, setView] = useState<'chart' | 'grid'>('chart')

  const { data: brainStatsData } = useBrainStats()
  const brain = brainStatsData?.tables
    ? {
        ...systemData?.brain,
        ...brainStatsData.tables,
        wants: brainStatsData.wants || 0,
        dont_wants: brainStatsData.dont_wants || 0,
        strategic_intents: brainStatsData.strategic_intents || 0,
        extraction_rate: systemData?.brain?.extraction_rate || 0,
        graph_nodes: brainStatsData?.graph?.nodes || 0,
        graph_edges: brainStatsData?.graph?.edges || 0,
      }
    : systemData?.brain || {}

  const lessons = brain.lessons || 0
  const failures = brain.failures || 0
  const patterns = brain.patterns || 0
  const wants = brain.wants || 0
  const dont_wants = brain.dont_wants || 0
  const intents = brain.intents || 0
  const strategic_intents = brain.strategic_intents || 0
  const anti_patterns = brain.anti_patterns || 0
  const evidence_items = brain.evidence || 0
  const graph_nodes = brain.graph_nodes || 0
  const graph_edges = brain.graph_edges || 0
  const extraction_rate =
    typeof brain.extraction_rate === 'number' ? brain.extraction_rate : 0

  const healthScore = useMemo(() => computeHealthScore(brain), [brain])

  /* recharts data — active brain categories (schemas/procedures removed — legacy regex data) */
  const facts = brain.facts || 0
  const schemas = brain.schemas || 0
  const episodic = brain.episodic || 0
  const barData = [
    { name: 'Lessons', count: lessons },
    { name: 'Failures', count: failures },
    { name: 'Patterns', count: patterns },
    { name: 'Wants', count: wants },
    { name: "Don'ts", count: dont_wants },
    { name: 'Facts', count: facts },
    { name: 'Schemas', count: schemas },
    { name: 'Intents', count: strategic_intents },
    { name: 'Episodic', count: episodic },
    { name: 'Anti-Patterns', count: anti_patterns },
  ]

  const gaugeData = [{ name: 'Rate', value: Math.min(extraction_rate, 100) }]
  const gaugeColor =
    extraction_rate >= 30
      ? '#34d399'
      : extraction_rate >= 10
        ? '#fbbf24'
        : '#fb7185'

  const healthGaugeData = [{ name: 'Health', value: healthScore }]

  /* Knowledge distribution area chart data */
  const distributionData = useMemo(() => [
    { region: 'Lessons', items: lessons },
    { region: 'Failures', items: failures },
    { region: 'Patterns', items: patterns },
    { region: 'Wants', items: wants },
    { region: "Don't Wants", items: dont_wants },
    { region: 'Intents', items: intents },
    { region: 'Anti-Patterns', items: anti_patterns },
  ], [lessons, failures, patterns, wants, dont_wants, intents, anti_patterns, strategic_intents])

  /* Trend indicators based on relative values */
  const lessonTrend: 'up' | 'down' | 'flat' = lessons > 10 ? 'up' : lessons > 0 ? 'flat' : 'down'
  const failureTrend: 'up' | 'down' | 'flat' = failures > 5 ? 'up' : failures > 0 ? 'flat' : 'down'
  const patternTrend: 'up' | 'down' | 'flat' = patterns > 5 ? 'up' : patterns > 0 ? 'flat' : 'down'

  if (loading) {
    return (
      <div className="space-y-3">
        <h2 className="text-lg font-semibold text-slate-300 mb-4">
          Brain Health
        </h2>
        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-8 flex items-center justify-center">
          <div className="flex items-center gap-3">
            <span className="w-2 h-2 rounded-full bg-sky-400 animate-pulse" />
            <p className="text-sm text-slate-500">Loading neural status...</p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div>
      {/* Header + view toggle */}
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-slate-300">Brain Health</h2>
        <div className="flex gap-1 bg-slate-800/60 rounded-lg p-1">
          <button
            onClick={() => setView('chart')}
            className={`text-xs px-3 py-1 rounded-md transition-colors ${
              view === 'chart'
                ? 'bg-sky-600/40 text-sky-300'
                : 'text-slate-500 hover:text-slate-300'
            }`}
          >
            Chart
          </button>
          <button
            onClick={() => setView('grid')}
            className={`text-xs px-3 py-1 rounded-md transition-colors ${
              view === 'grid'
                ? 'bg-sky-600/40 text-sky-300'
                : 'text-slate-500 hover:text-slate-300'
            }`}
          >
            Grid
          </button>
        </div>
      </div>

      {/* ── Chart view ── */}
      {view === 'chart' && (
        <div className="space-y-4">
          {/* Row 1: Health score + Extraction rate + Knowledge distribution */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* Health score gauge */}
            <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-4 flex flex-col items-center justify-center">
              <p className="text-xs font-medium text-slate-400 uppercase tracking-wider mb-2">
                Health Score
              </p>
              <ResponsiveContainer width="100%" height={130}>
                <RadialBarChart
                  cx="50%"
                  cy="50%"
                  innerRadius="65%"
                  outerRadius="85%"
                  startAngle={180}
                  endAngle={0}
                  data={healthGaugeData}
                >
                  <PolarAngleAxis
                    type="number"
                    domain={[0, 100]}
                    angleAxisId={0}
                    tick={false}
                  />
                  <RadialBar
                    dataKey="value"
                    cornerRadius={8}
                    fill={healthColor(healthScore)}
                    background={{ fill: 'rgba(51,65,85,0.5)' }}
                  />
                </RadialBarChart>
              </ResponsiveContainer>
              <p className="text-2xl font-bold -mt-2" style={{ color: healthColor(healthScore) }}>
                {healthScore}
              </p>
              <p className="text-xs text-slate-500 mt-0.5">{healthLabel(healthScore)}</p>
            </div>

            {/* Extraction rate gauge */}
            <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-4 flex flex-col items-center justify-center">
              <p className="text-xs font-medium text-slate-400 uppercase tracking-wider mb-2">
                Extraction Rate
              </p>
              <ResponsiveContainer width="100%" height={130}>
                <RadialBarChart
                  cx="50%"
                  cy="50%"
                  innerRadius="65%"
                  outerRadius="85%"
                  startAngle={180}
                  endAngle={0}
                  data={gaugeData}
                >
                  <PolarAngleAxis
                    type="number"
                    domain={[0, 100]}
                    angleAxisId={0}
                    tick={false}
                  />
                  <RadialBar
                    dataKey="value"
                    cornerRadius={8}
                    fill={gaugeColor}
                    background={{ fill: 'rgba(51,65,85,0.5)' }}
                  />
                </RadialBarChart>
              </ResponsiveContainer>
              <p className={`text-2xl font-bold -mt-2 ${
                extraction_rate >= 30 ? 'text-emerald-400' :
                extraction_rate >= 10 ? 'text-amber-400' :
                'text-rose-400'
              }`}>
                {extraction_rate.toFixed(1)}%
              </p>
              <p className="text-xs text-slate-500 mt-0.5">Target: 30-40%</p>
            </div>

            {/* Knowledge distribution area chart */}
            <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-4">
              <p className="text-xs font-medium text-slate-400 uppercase tracking-wider mb-3">
                Knowledge Distribution
              </p>
              <ResponsiveContainer width="100%" height={150}>
                <AreaChart data={distributionData}>
                  <defs>
                    <linearGradient id="brainGrad" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#38bdf8" stopOpacity={0.4} />
                      <stop offset="100%" stopColor="#38bdf8" stopOpacity={0.05} />
                    </linearGradient>
                  </defs>
                  <XAxis
                    dataKey="region"
                    axisLine={false}
                    tickLine={false}
                    tick={{ fill: '#94a3b8', fontSize: 10 }}
                  />
                  <YAxis hide />
                  <Tooltip content={<ChartTooltip />} cursor={false} />
                  <Area
                    type="monotone"
                    dataKey="items"
                    stroke="#38bdf8"
                    strokeWidth={2}
                    fill="url(#brainGrad)"
                  />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Row 2: Bar chart — knowledge breakdown */}
          <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-4">
            <p className="text-xs font-medium text-slate-400 uppercase tracking-wider mb-3">
              Knowledge Breakdown
            </p>
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={barData} barSize={28}>
                <XAxis
                  dataKey="name"
                  axisLine={false}
                  tickLine={false}
                  tick={{ fill: '#94a3b8', fontSize: 11 }}
                />
                <YAxis
                  axisLine={false}
                  tickLine={false}
                  tick={{ fill: '#64748b', fontSize: 11 }}
                  width={40}
                />
                <Tooltip content={<ChartTooltip />} cursor={false} />
                <Bar dataKey="count" radius={[4, 4, 0, 0]}>
                  {barData.map((_, i) => (
                    <Cell key={i} fill={BAR_COLORS[i % BAR_COLORS.length]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      )}

      {/* ── Grid view (stat cards with trends) ── */}
      {view === 'grid' && (
        <div className="grid grid-cols-3 md:grid-cols-5 gap-3 mb-6">
          <StatCard label="Lessons" value={lessons.toLocaleString()} trend={lessonTrend} />
          <StatCard label="Failures" value={failures.toLocaleString()} trend={failureTrend} />
          <StatCard label="Patterns" value={patterns.toLocaleString()} trend={patternTrend} />
          <StatCard label="Wants" value={wants.toLocaleString()} />
          <StatCard label="Don'ts" value={dont_wants.toLocaleString()} />
          <StatCard label="Facts" value={facts.toLocaleString()} />
          <StatCard label="Schemas" value={schemas.toLocaleString()} />
          <StatCard label="Intents" value={intents.toLocaleString()} />
          <StatCard label="Strategic" value={strategic_intents.toLocaleString()} />
          <StatCard label="Episodic" value={episodic.toLocaleString()} />
          <StatCard label="Anti-Patterns" value={anti_patterns.toLocaleString()} />
        </div>
      )}

      {/* Evidence pipeline + graph summary bar */}
      <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-4 flex items-center gap-4 mt-4">
        <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
        <p className="text-sm text-slate-300 font-medium">Neural System Online</p>
        <div className="flex items-center gap-3 ml-auto text-xs text-slate-500">
          <span className="text-slate-400">{evidence_items.toLocaleString()} evidence</span>
          <span className="text-slate-700">&rarr;</span>
          <span className="text-sky-400">{(lessons + failures + patterns + wants + dont_wants + intents + anti_patterns).toLocaleString()} knowledge items</span>
          <span className="text-slate-700">|</span>
          <span>{graph_nodes} nodes</span>
          <span className="text-slate-700">&middot;</span>
          <span>{graph_edges} edges</span>
          <span className="text-slate-700">|</span>
          <span style={{ color: healthColor(healthScore) }}>{healthScore}/100</span>
        </div>
      </div>
    </div>
  )
}
