import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

interface BySource {
  source: string;
  median_tokens_per_msg: number;
  sessions: number;
  pct_accelerating: number;
}

interface ChartData {
  token_growth?: {
    headline: string;
    total_sessions_analyzed: number;
    accelerating_sessions: number;
    median_tokens_per_msg: number;
    by_source: BySource[];
    acceleration_distribution?: { range: string; count: number }[];
  };
}

const SOURCE_COLORS: Record<string, string> = {
  claude_code: '#6366f1',
  codex_cli: '#f43f5e',
  gemini_cli: '#f59e0b',
};

const SOURCE_LABELS: Record<string, string> = {
  claude_code: 'Claude Code',
  codex_cli: 'Codex CLI',
  gemini_cli: 'Gemini CLI',
};

export default function TokenGrowth() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {});

  if (loading || !data.token_growth) return null;

  const tg = data.token_growth;
  const pctAccelerating = tg.total_sessions_analyzed > 0
    ? ((tg.accelerating_sessions / tg.total_sessions_analyzed) * 100).toFixed(1)
    : '0';

  const accelData = tg.by_source.map(s => ({
    name: SOURCE_LABELS[s.source] || s.source,
    '% Accelerating': s.pct_accelerating,
    fill: SOURCE_COLORS[s.source] || '#6366f1',
  }));

  const tokenData = tg.by_source.map(s => ({
    name: SOURCE_LABELS[s.source] || s.source,
    'Median Tokens/Msg': s.median_tokens_per_msg,
    fill: SOURCE_COLORS[s.source] || '#6366f1',
  }));

  return (
    <section className="px-8 max-w-7xl mx-auto py-16">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true }}
        transition={{ duration: 0.6 }}
      >
        <h2 className="text-3xl md:text-4xl font-bold mb-2">
          <span className="text-amber">{tg.accelerating_sessions}</span> sessions show runaway token growth.
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          {pctAccelerating}% of sessions consume tokens faster in their second half than their first — a sign of context window pressure that inflates costs super-linearly.
        </p>
      </motion.div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mb-6">
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5 text-center"
        >
          <div className="text-3xl font-bold text-amber">{tg.accelerating_sessions}</div>
          <div className="text-xs text-text-3 mt-1">accelerating sessions</div>
        </motion.div>
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.08 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5 text-center"
        >
          <div className="text-3xl font-bold text-text-1">{tg.total_sessions_analyzed}</div>
          <div className="text-xs text-text-3 mt-1">sessions analyzed</div>
        </motion.div>
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.16 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5 text-center"
        >
          <div className="text-3xl font-bold text-text-1">{tg.median_tokens_per_msg.toLocaleString()}</div>
          <div className="text-xs text-text-3 mt-1">median tokens/message</div>
        </motion.div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.1 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5"
        >
          <h3 className="text-sm font-semibold text-text-2 mb-4">% Sessions with Accelerating Tokens (by CLI)</h3>
          <ResponsiveContainer width="100%" height={180}>
            <BarChart data={accelData} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis type="number" tick={{ fill: '#888', fontSize: 11 }} tickFormatter={v => `${v}%`} domain={[0, 'auto']} />
              <YAxis type="category" dataKey="name" width={100} tick={{ fill: '#ccc', fontSize: 12 }} />
              <Tooltip
                contentStyle={{ background: '#1a1a2e', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, fontSize: 12 }}
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                formatter={((v: any) => [`${Number(v ?? 0).toFixed(1)}%`, '% Accelerating']) as any}
              />
              <Bar dataKey="% Accelerating" radius={[0, 4, 4, 0]}>
                {accelData.map((d, i) => (
                  <motion.rect key={i} fill={d.fill} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5"
        >
          <h3 className="text-sm font-semibold text-text-2 mb-4">Median Tokens per Message (by CLI)</h3>
          <ResponsiveContainer width="100%" height={180}>
            <BarChart data={tokenData} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis type="number" tick={{ fill: '#888', fontSize: 11 }} tickFormatter={v => v >= 1000 ? `${(v/1000).toFixed(0)}K` : v} />
              <YAxis type="category" dataKey="name" width={100} tick={{ fill: '#ccc', fontSize: 12 }} />
              <Tooltip
                contentStyle={{ background: '#1a1a2e', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, fontSize: 12 }}
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                formatter={((v: any) => [Number(v ?? 0).toLocaleString(), 'Tokens/Msg']) as any}
              />
              <Bar dataKey="Median Tokens/Msg" radius={[0, 4, 4, 0]}>
                {tokenData.map((d, i) => (
                  <motion.rect key={i} fill={d.fill} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </motion.div>
      </div>

      <motion.div
        initial={{ opacity: 0 }}
        whileInView={{ opacity: 1 }}
        viewport={{ once: true }}
        transition={{ delay: 0.4 }}
        className="mt-4 bg-amber/5 border border-amber/20 rounded-xl px-5 py-3 text-sm text-text-2"
      >
        Sessions with accelerating token growth should be split into smaller, focused sessions. Codex CLI sessions show 33% acceleration rate — resetting context more frequently could reduce token costs significantly.
      </motion.div>
    </section>
  );
}
