import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from 'recharts';

interface Arc {
  arc: string;
  label: string;
  count: number;
}

interface SessionArcsData {
  session_arcs: {
    arcs: Arc[];
    headline: string;
    total_sessions: number;
  };
}

const ARC_COLORS: Record<string, string> = {
  full_cycle: '#34d399',
  shell_only: '#22d3ee',
  explore_then_edit: '#818cf8',
  explore_only: '#fb7185',
  quick_lookup: '#fbbf24',
  mixed: '#a78bfa',
  direct_edit: '#f472b6',
};

const ARC_LABELS: Record<string, string> = {
  full_cycle: '01',
  shell_only: '02',
  explore_then_edit: '03',
  explore_only: '04',
  quick_lookup: '05',
  mixed: '06',
  direct_edit: '07',
};

const CustomTooltip = ({ active, payload }: any) => {
  if (!active || !payload?.length) return null;
  const d = payload[0]?.payload;
  return (
    <div className="bg-surface-3 border border-border-dim rounded-lg px-3 py-2 text-xs shadow-xl">
      <div className="text-text-2 mb-1">{d?.label}</div>
      <div className="text-text-1 font-semibold">{d?.count} sessions ({d?.pct}%)</div>
    </div>
  );
};

export default function SessionArcs() {
  const { data, loading } = useData<SessionArcsData>('/data/chart_data.json', {
    session_arcs: { arcs: [], headline: '', total_sessions: 0 },
  });

  const arcs = data.session_arcs?.arcs || [];
  const total = data.session_arcs?.total_sessions || 1;

  if (loading || !arcs.length) return null;

  const pieData = arcs.map(a => ({
    ...a,
    pct: ((a.count / total) * 100).toFixed(1),
    fill: ARC_COLORS[a.arc] || '#63637a',
  }));

  const topArc = arcs[0];
  const exploreOnly = arcs.find(a => a.arc === 'explore_only');
  const shellOnly = arcs.find(a => a.arc === 'shell_only');

  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">
          Only {topArc ? ((topArc.count / total) * 100).toFixed(0) : '?'}% of sessions complete the full cycle.
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          A "full cycle" means the AI explored code, made edits, and ran tests. {shellOnly ? `${shellOnly.count} sessions (${((shellOnly.count / total) * 100).toFixed(0)}%) ran shell commands without touching any files.` : ''}
          {exploreOnly ? ` Another ${exploreOnly.count} sessions just read files and gave up.` : ''}
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Donut chart */}
        <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 Pattern Distribution
          </h3>
          <ResponsiveContainer width="100%" height={280}>
            <PieChart>
              <Pie
                data={pieData}
                dataKey="count"
                nameKey="label"
                cx="50%"
                cy="50%"
                innerRadius={60}
                outerRadius={110}
                paddingAngle={2}
                strokeWidth={0}
              >
                {pieData.map((d, i) => (
                  <Cell key={i} fill={d.fill} />
                ))}
              </Pie>
              <Tooltip content={<CustomTooltip />} />
            </PieChart>
          </ResponsiveContainer>
          <div className="text-center text-xs text-text-3 -mt-2">
            {total} sessions classified
          </div>
        </motion.div>

        {/* Ranked list */}
        <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 Patterns Ranked
          </h3>
          <div className="space-y-2.5">
            {pieData.map((arc, i) => {
              const pct = (arc.count / total) * 100;
              return (
                <motion.div
                  key={arc.arc}
                  initial={{ opacity: 0, x: -20 }}
                  whileInView={{ opacity: 1, x: 0 }}
                  viewport={{ once: true }}
                  transition={{ delay: 0.3 + i * 0.06, duration: 0.4 }}
                  className="flex items-center gap-3"
                >
                  <span className="text-xs font-mono w-8 text-center shrink-0 text-text-3">{ARC_LABELS[arc.arc] || '#'}</span>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm text-text-1 font-medium truncate">{arc.label}</span>
                      <span className="text-xs text-text-2 font-mono shrink-0 ml-2">{arc.count} ({arc.pct}%)</span>
                    </div>
                    <div className="h-1.5 bg-surface-3 rounded-full overflow-hidden">
                      <motion.div
                        initial={{ width: 0 }}
                        whileInView={{ width: `${pct}%` }}
                        viewport={{ once: true }}
                        transition={{ delay: 0.5 + i * 0.06, duration: 0.6, ease: 'easeOut' }}
                        className="h-full rounded-full"
                        style={{ background: arc.fill }}
                      />
                    </div>
                  </div>
                </motion.div>
              );
            })}
          </div>
        </motion.div>
      </div>
    </section>
  );
}
