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

interface EfficiencyEntry {
  developer: string;
  edit_count: number;
  estimated_cost: number;
  edits_per_dollar: number;
}

interface Overview {
  developer_efficiency?: EfficiencyEntry[];
  cost_per_productive_session?: number;
  productive_cost_multiplier?: number;
  cost_per_productive_session_note?: string;
}

const DARK_TOOLTIP = {
  contentStyle: { background: '#1a1a2e', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, color: '#e2e8f0' },
  itemStyle: { color: '#e2e8f0' },
};

const BAR_COLORS = ['#34d399', '#fbbf24', '#fb7185'];

function shortEmail(email: string): string {
  const at = email.indexOf('@');
  if (at < 0) return email;
  const name = email.slice(0, at);
  // Handle GitHub noreply format
  if (name.includes('+')) return name.split('+')[1] || name;
  return name.split('.')[0] || name;
}

export default function DeveloperEfficiency() {
  const { data, loading } = useData<Overview>('/data/overview.json', {});

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

  const devs = [...data.developer_efficiency].sort((a, b) => b.edits_per_dollar - a.edits_per_dollar);
  const best = devs[0];
  const worst = devs[devs.length - 1];
  const ratio = best && worst && worst.edits_per_dollar > 0
    ? (best.edits_per_dollar / worst.edits_per_dollar).toFixed(1)
    : null;

  const chartData = devs.map(d => ({
    name: shortEmail(d.developer),
    edits_per_dollar: d.edits_per_dollar,
    edit_count: d.edit_count,
    cost: d.estimated_cost,
  }));

  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">
          {ratio ? (
            <>{ratio}x gap in ROI per dollar spent.</>
          ) : (
            <>Not all AI dollars are equal.</>
          )}
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          Edits per dollar measures how many code changes each developer gets for every dollar of AI spend.
          The question isn't who spends the most — it's who gets the most value.
          <span className="inline-flex items-center ml-1"><CostInfoTip /></span>
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Bar 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-6"
        >
          <div className="text-xs text-text-3 uppercase tracking-wider mb-4">Edits per Dollar</div>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={chartData} layout="vertical" margin={{ left: 10, right: 40, top: 5, bottom: 5 }}>
              <XAxis type="number" tick={{ fontSize: 10, fill: '#a1a1aa' }} axisLine={false} tickLine={false} />
              <YAxis type="category" dataKey="name" width={70} tick={{ fontSize: 12, fill: '#e2e8f0', fontWeight: 600 }} axisLine={false} tickLine={false} />
              <Tooltip
                {...DARK_TOOLTIP}
                formatter={(value: number, _name: string, props: any) => {
                  const d = props.payload;
                  return [`${value} edits/$ (${d.edit_count} edits, $${d.cost.toFixed(0)} spent)`, 'Efficiency'];
                }}
              />
              <Bar dataKey="edits_per_dollar" radius={[0, 6, 6, 0]} barSize={32}>
                {chartData.map((_d, i) => (
                  <Cell key={i} fill={BAR_COLORS[i] || '#818cf8'} fillOpacity={0.85} />
                ))}
                <LabelList dataKey="edits_per_dollar" position="right" fill="#e2e8f0" fontSize={13} fontWeight={700} formatter={(v: number) => `${v}/\$`} />
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </motion.div>

        {/* Detail cards */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2, duration: 0.5 }}
          className="space-y-3"
        >
          {devs.map((d, i) => (
            <div key={d.developer} className={`bg-surface-1 border rounded-xl p-4 flex items-center gap-4 ${i === 0 ? 'border-green/30' : i === devs.length - 1 ? 'border-rose/30' : 'border-border-dim'}`}>
              <div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${i === 0 ? 'bg-green/15 text-green' : i === devs.length - 1 ? 'bg-rose/15 text-rose' : 'bg-amber/15 text-amber'}`}>
                {d.edits_per_dollar}
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-sm font-semibold text-text-1">{shortEmail(d.developer)}</div>
                <div className="text-xs text-text-3">{d.edit_count} edits from ${d.estimated_cost.toFixed(0)} spend</div>
              </div>
              <div className="text-right shrink-0">
                <div className="text-xs text-text-3">edits/$</div>
                <div className={`text-lg font-bold ${i === 0 ? 'text-green' : i === devs.length - 1 ? 'text-rose' : 'text-amber'}`}>
                  {d.edits_per_dollar}
                </div>
              </div>
            </div>
          ))}

          {data.cost_per_productive_session != null && (
            <div className="bg-surface-2 border border-border-dim rounded-xl p-4 text-xs text-text-3 leading-relaxed">
              Context: Each productive session (with edits) costs <span className="text-rose font-semibold">${data.cost_per_productive_session.toFixed(2)}</span> vs <span className="text-text-2 font-semibold">${((data.cost_per_productive_session ?? 0) / (data.productive_cost_multiplier ?? 1)).toFixed(2)}</span>/avg session — a {data.productive_cost_multiplier}x multiplier because {Math.round((1 - 1 / (data.productive_cost_multiplier ?? 1)) * 100)}% of sessions produce zero edits.
            </div>
          )}
        </motion.div>
      </div>
    </section>
  );
}
