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

interface ScatterAnnotation {
  label: string;
  description: string;
  x?: number;
  y?: number;
  count?: number;
}

interface ChartData {
  duration_histogram: { counts: number[]; edges: number[] };
  session_scatter: Array<{
    session_id: string;
    duration_min: number;
    input_tokens: number;
    output_tokens: number;
    source: string;
  }>;
  scatter_annotations?: ScatterAnnotation[];
  duration_breakdown?: Record<string, number>;
}

const SOURCE_COLORS: Record<string, string> = {
  claude_code: '#818cf8',
  codex_cli: '#34d399',
  gemini_cli: '#22d3ee',
  cursor: '#fbbf24',
  test: '#63637a',
  qc_trace_install: '#63637a',
};

const CustomTooltip = ({ active, payload }: any) => {
  if (!active || !payload?.length) return null;
  const d = payload[0]?.payload;
  if (!d) return null;
  return (
    <div className="bg-surface-3 border border-border-dim rounded-lg px-3 py-2 text-xs shadow-xl">
      {d.range ? (
        <>
          <div className="text-text-2">{d.range} min</div>
          <div className="text-text-1 font-semibold">{d.count} sessions</div>
        </>
      ) : (
        <>
          <div className="text-text-2">{d.source?.replace('_', ' ')}</div>
          <div className="text-text-1">{d.duration_min?.toFixed(1)} min</div>
          <div className="text-text-3">{d.output_tokens?.toLocaleString()} output tokens</div>
        </>
      )}
    </div>
  );
};

export default function SessionDistribution() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {
    duration_histogram: { counts: [], edges: [] },
    session_scatter: [],
  });

  if (loading) return null;

  const { counts, edges } = data.duration_histogram;
  const histData = counts.map((count, i) => ({
    range: `${edges[i]}-${edges[i + 1]}`,
    count,
    label: `${edges[i]}`,
  }));

  // Filter scatter to meaningful sessions (exclude test/install, cap at 120 min for viz)
  const scatterData = (data.session_scatter || [])
    .filter(s => !['test', 'qc_trace_install'].includes(s.source) && s.output_tokens > 0)
    .map(s => ({
      ...s,
      duration_capped: Math.min(s.duration_min, 120),
      output_capped: Math.min(s.output_tokens, 50000),
    }));

  return (
    <section className="px-8 max-w-7xl mx-auto py-20">
      <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">
          {(() => {
            const under5 = counts.reduce((acc: number, c: number, i: number) => edges[i] < 5 ? acc + c : acc, 0);
            const total = counts.reduce((a: number, b: number) => a + b, 0);
            return `${total > 0 ? Math.round((under5 / total) * 100) : 80}% of sessions are under 5 minutes.`;
          })()}
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          Most AI coding sessions are short, focused interactions. Note: duration shown is wall-clock time
          (first to last message). Active AI time excludes idle gaps over 30 minutes — see the Active Time section for that metric.
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Duration histogram */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.1, duration: 0.5 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
            Session Duration Distribution (minutes)
          </h3>
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={histData} margin={{ bottom: 20 }}>
              <XAxis
                dataKey="label"
                tick={{ fontSize: 10 }}
                interval={1}
                label={{ value: 'Minutes', position: 'insideBottom', offset: -10, fontSize: 11, fill: '#63637a' }}
              />
              <YAxis tick={{ fontSize: 10 }} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="count" fill="#818cf8" radius={[3, 3, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
          {(() => {
            // Compute from histogram: sum bins where edge < 5
            const under5 = counts.reduce((acc, c, i) => edges[i] < 5 ? acc + c : acc, 0);
            const total = counts.reduce((a, b) => a + b, 0);
            const pct = total > 0 ? Math.round((under5 / total) * 100) : 0;
            return total > 0 ? <div className="mt-2 text-xs text-text-3 text-center">{under5} sessions ({pct}%) completed in under 5 minutes</div> : null;
          })()}
        </motion.div>

        {/* Scatter: duration vs output tokens */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2, duration: 0.5 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
            Session Duration vs Output (color = CLI)
          </h3>
          <ResponsiveContainer width="100%" height={300}>
            <ScatterChart margin={{ bottom: 20, left: 10, right: 10 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#27272f" />
              <XAxis
                dataKey="duration_capped"
                name="Duration"
                type="number"
                tick={{ fontSize: 10 }}
                label={{ value: 'Duration (min)', position: 'insideBottom', offset: -10, fontSize: 11, fill: '#63637a' }}
              />
              <YAxis
                dataKey="output_capped"
                name="Output Tokens"
                type="number"
                tick={{ fontSize: 10 }}
                label={{ value: 'Output Tokens', angle: -90, position: 'insideLeft', fontSize: 11, fill: '#63637a' }}
              />
              <ZAxis range={[15, 15]} />
              <ReferenceLine x={30} stroke="#27272f" strokeDasharray="6 3" label={{ value: '30 min', position: 'top', fontSize: 9, fill: '#63637a' }} />
              <ReferenceLine y={15000} stroke="#27272f" strokeDasharray="6 3" />
              {/* Quadrant labels as custom reference lines with labels */}
              <ReferenceLine x={5} stroke="transparent" label={{ value: 'Quick wins', position: 'insideTopLeft', fontSize: 9, fill: '#34d399' }} />
              <ReferenceLine x={90} stroke="transparent" label={{ value: 'Marathons', position: 'insideTopRight', fontSize: 9, fill: '#fbbf24' }} />
              <ReferenceLine x={90} stroke="transparent" label={{ value: 'Spinning wheels', position: 'insideBottomRight', fontSize: 9, fill: '#fb7185' }} />
              <ReferenceLine x={5} stroke="transparent" label={{ value: 'Trivial', position: 'insideBottomLeft', fontSize: 9, fill: '#63637a' }} />
              <Tooltip content={<CustomTooltip />} />
              <Scatter data={scatterData}>
                {scatterData.map((d, i) => (
                  <Cell
                    key={i}
                    fill={SOURCE_COLORS[d.source] || '#63637a'}
                    opacity={0.7}
                  />
                ))}
              </Scatter>
            </ScatterChart>
          </ResponsiveContainer>
          <div className="flex flex-wrap gap-3 justify-center mt-2">
            {Object.entries(SOURCE_COLORS)
              .filter(([k]) => !['test', 'qc_trace_install'].includes(k))
              .map(([k, c]) => (
                <div key={k} className="flex items-center gap-1.5 text-xs text-text-3">
                  <div className="w-2.5 h-2.5 rounded-full" style={{ background: c }} />
                  {k.replace('_', ' ')}
                </div>
              ))}
          </div>
          {/* Scatter annotations from data */}
          {(data.scatter_annotations || []).length > 0 ? (
            <div className="mt-3 space-y-2">
              {data.scatter_annotations!.map((ann, i) => (
                <div key={i} className={`rounded-lg p-3 text-xs text-text-2 ${
                  ann.label === 'Insight' ? 'bg-accent/5 border border-accent/20' : 'bg-surface-2 border border-border-dim'
                }`}>
                  <span className={`font-semibold ${ann.label === 'Insight' ? 'text-accent' : 'text-text-1'}`}>
                    {ann.label}:
                  </span>{' '}
                  {ann.description}
                </div>
              ))}
            </div>
          ) : (
            <div className="mt-3 bg-accent/5 border border-accent/20 rounded-lg p-3 text-xs text-text-2">
              <span className="font-semibold text-accent">Key insight:</span>{' '}
              Longer sessions don't produce more output. The most productive AI work is short and focused.
            </div>
          )}
        </motion.div>
      </div>
    </section>
  );
}
