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

interface HourEntry {
  hour: number;
  zero_edit_pct: number;
  total_sessions?: number;
  zero_edit_sessions?: number;
}

interface ChartData {
  zero_edit_rate_by_hour?: HourEntry[];
}

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

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

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

  const raw = data.zero_edit_rate_by_hour;
  const chartData = raw
    .map(d => ({
      ...d,
      label: formatHour(d.hour),
      displayHour: offsetHour(d.hour),
      pct: Math.round(d.zero_edit_pct),
    }))
    .sort((a, b) => a.displayHour - b.displayHour);

  const avgPct = Math.round(chartData.reduce((s, d) => s + d.pct, 0) / chartData.length);
  const worst = chartData.reduce((w, d) => d.pct > w.pct ? d : w, chartData[0]);

  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">
          After {worst.label}, <span className="text-rose">{worst.pct}%</span> of sessions produce nothing.
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          Zero-edit rate by hour of day. Sessions that produce no code edits are effectively
          wasted AI spend. The average zero-edit rate is {avgPct}% — but it varies dramatically by time of day.
        </p>
      </motion.div>

      <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"
      >
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={chartData} margin={{ top: 10, right: 20, bottom: 10, left: 10 }}>
            <XAxis
              dataKey="label"
              tick={{ fontSize: 10, fill: '#a1a1aa' }}
              axisLine={{ stroke: '#27272f' }}
              tickLine={false}
            />
            <YAxis
              domain={[0, 100]}
              tick={{ fontSize: 10, fill: '#a1a1aa' }}
              axisLine={false}
              tickLine={false}
              tickFormatter={v => `${v}%`}
            />
            <Tooltip
              {...DARK_TOOLTIP}
              formatter={(value: number) => [`${value}%`, 'Zero-edit rate']}
              labelFormatter={(label: string) => `Hour: ${label}`}
            />
            <ReferenceLine y={avgPct} stroke="#818cf8" strokeDasharray="4 4" label={{ value: `avg ${avgPct}%`, position: 'right', fill: '#818cf8', fontSize: 10 }} />
            <Bar dataKey="pct" radius={[4, 4, 0, 0]}>
              {chartData.map((d, i) => (
                <Cell key={i} fill={d.pct >= 75 ? '#fb7185' : d.pct >= 50 ? '#fbbf24' : '#34d399'} fillOpacity={0.8} />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>

        <div className="mt-3 text-xs text-text-3 text-center">
          Session time = sum of AI response times, excluding idle gaps &gt; 30 min.
          Zero-edit = session with no file write/edit tool calls.
        </div>
      </motion.div>
    </section>
  );
}
