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

interface CLISource {
  source: string;
  sessions: number;
  cost_total: number;
  cost_per_session: number;
  edits_per_session: number;
  explores_per_session: number;
  pct_of_total_cost: number;
}

interface ChartData {
  cli_comparison?: {
    headline: string;
    sources: CLISource[];
  };
}

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 CLIComparison() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {});

  if (loading || !data.cli_comparison?.sources?.length) return null;

  const { headline, sources } = data.cli_comparison;

  const costData = sources.map(s => ({
    name: SOURCE_LABELS[s.source] || s.source,
    'Cost per Session': s.cost_per_session,
    fill: SOURCE_COLORS[s.source] || '#6366f1',
  }));

  const shareData = sources.map(s => ({
    name: SOURCE_LABELS[s.source] || s.source,
    sessions: s.sessions,
    cost_pct: s.pct_of_total_cost,
    fill: SOURCE_COLORS[s.source] || '#6366f1',
  }));

  // Radar comparison — normalize each metric to 0-100 for visual comparison
  const maxSessions = Math.max(...sources.map(s => s.sessions));
  const maxCost = Math.max(...sources.map(s => s.cost_per_session));
  const maxEdits = Math.max(...sources.map(s => s.edits_per_session), 1);
  const maxExplores = Math.max(...sources.map(s => s.explores_per_session), 1);

  const radarData = [
    { metric: 'Sessions', ...Object.fromEntries(sources.map(s => [s.source, (s.sessions / maxSessions) * 100])) },
    { metric: 'Cost/Session', ...Object.fromEntries(sources.map(s => [s.source, (s.cost_per_session / maxCost) * 100])) },
    { metric: 'Edits/Session', ...Object.fromEntries(sources.map(s => [s.source, (s.edits_per_session / maxEdits) * 100])) },
    { metric: 'Explores/Session', ...Object.fromEntries(sources.map(s => [s.source, (s.explores_per_session / maxExplores) * 100])) },
    { metric: 'Cost Share %', ...Object.fromEntries(sources.map(s => [s.source, s.pct_of_total_cost])) },
  ];

  const codex = sources.find(s => s.source === 'codex_cli');
  const claude = sources.find(s => s.source === 'claude_code');
  const multiplier = codex && claude && claude.cost_per_session > 0
    ? Math.round(codex.cost_per_session / claude.cost_per_session)
    : null;

  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">
          {multiplier
            ? <>One CLI costs <span className="text-rose">{multiplier}x</span> more per session.</>
            : headline}
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          Head-to-head comparison of AI CLI tools used by your team. The cost gap is not incremental — it's orders of magnitude.
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Cost per session bar chart */}
        <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">Cost per Session (USD)</h3>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={costData} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis type="number" tick={{ fill: '#888', fontSize: 11 }} tickFormatter={v => `$${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).toFixed(2)}`, 'Cost/Session']) as any}
              />
              <Bar dataKey="Cost per Session" radius={[0, 4, 4, 0]}>
                {costData.map((d, i) => (
                  <motion.rect key={i} fill={d.fill} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </motion.div>

        {/* Radar comparison */}
        <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">Capability Profile</h3>
          <ResponsiveContainer width="100%" height={240}>
            <RadarChart data={radarData}>
              <PolarGrid stroke="rgba(255,255,255,0.08)" />
              <PolarAngleAxis dataKey="metric" tick={{ fill: '#888', fontSize: 10 }} />
              {sources.map(s => (
                <Radar
                  key={s.source}
                  dataKey={s.source}
                  name={SOURCE_LABELS[s.source] || s.source}
                  stroke={SOURCE_COLORS[s.source] || '#6366f1'}
                  fill={SOURCE_COLORS[s.source] || '#6366f1'}
                  fillOpacity={0.12}
                  strokeWidth={1.5}
                />
              ))}
              <Legend wrapperStyle={{ fontSize: 11, color: '#aaa' }} />
            </RadarChart>
          </ResponsiveContainer>
        </motion.div>
      </div>

      {/* Stats cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mt-4">
        {sources.map((s, i) => (
          <motion.div
            key={s.source}
            initial={{ opacity: 0, y: 10 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ delay: 0.3 + i * 0.08 }}
            className="bg-surface-1 border border-border-dim rounded-xl p-4"
          >
            <div className="flex items-center gap-2 mb-3">
              <div className="w-2 h-2 rounded-full" style={{ background: SOURCE_COLORS[s.source] || '#6366f1' }} />
              <span className="text-sm font-semibold text-text-1">{SOURCE_LABELS[s.source] || s.source}</span>
            </div>
            <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-xs">
              <div><span className="text-text-3">Sessions</span><div className="text-text-1 font-semibold">{s.sessions}</div></div>
              <div><span className="text-text-3">Total Cost</span><div className="text-text-1 font-semibold">${s.cost_total.toFixed(0)}</div></div>
              <div><span className="text-text-3">Cost/Session</span><div className="font-semibold" style={{ color: SOURCE_COLORS[s.source] }}>${s.cost_per_session.toFixed(2)}</div></div>
              <div><span className="text-text-3">Cost Share</span><div className="text-text-1 font-semibold">{s.pct_of_total_cost.toFixed(1)}%</div></div>
              <div><span className="text-text-3">Edits/Session</span><div className="text-text-1 font-semibold">{s.edits_per_session.toFixed(1)}</div></div>
              <div><span className="text-text-3">Explores/Session</span><div className="text-text-1 font-semibold">{s.explores_per_session.toFixed(1)}</div></div>
            </div>
          </motion.div>
        ))}
      </div>

      {shareData.length > 0 && (
        <motion.div
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true }}
          transition={{ delay: 0.5 }}
          className="mt-4 bg-surface-1 border border-border-dim rounded-xl p-5"
        >
          <h3 className="text-sm font-semibold text-text-2 mb-3">Cost Share vs Session Share</h3>
          <div className="space-y-2">
            {shareData.map(s => (
              <div key={s.name} className="flex items-center gap-3">
                <span className="text-xs text-text-2 w-24 shrink-0">{s.name}</span>
                <div className="flex-1 flex items-center gap-2">
                  <div className="flex-1 h-5 bg-surface-2 rounded-full overflow-hidden relative">
                    <motion.div
                      className="h-full rounded-full"
                      style={{ background: s.fill }}
                      initial={{ width: 0 }}
                      whileInView={{ width: `${s.cost_pct}%` }}
                      viewport={{ once: true }}
                      transition={{ duration: 0.8, delay: 0.2 }}
                    />
                    <span className="absolute inset-0 flex items-center justify-center text-[10px] font-semibold text-text-1">
                      {s.cost_pct.toFixed(1)}% cost
                    </span>
                  </div>
                  <span className="text-[10px] text-text-3 w-20 text-right">{s.sessions} sessions</span>
                </div>
              </div>
            ))}
          </div>
        </motion.div>
      )}
    </section>
  );
}
