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

interface Insight {
  id: string;
  title: string;
  severity: string;
  metric: string;
  detail: string;
  recommendation: string;
  data: any;
}

function fileName(fp: string): string {
  const parts = fp.split('/');
  return parts[parts.length - 1] || fp;
}

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 max-w-xs">
      <div className="text-text-2 truncate">{d?.fullPath}</div>
      <div className="text-text-1 font-semibold mt-1">Read {d?.reads} times in one session</div>
    </div>
  );
};

export default function WastedReads() {
  const { data, loading } = useData<{ insights: Insight[] }>('/data/insights.json', { insights: [] });

  if (loading) return null;

  const repeatedReads = data.insights.find(i => i.id === 'repeated_reads');
  if (!repeatedReads?.data || !Array.isArray(repeatedReads.data)) return null;

  const top10 = repeatedReads.data.slice(0, 10).map((d: any) => ({
    file: fileName(d.file_path),
    fullPath: d.file_path,
    reads: d.read_count,
  }));

  const totalWasted = repeatedReads.data.reduce((sum: number, d: any) => sum + (d.read_count - 1), 0);

  const colors = [
    '#fb7185', '#fb7185', '#fb7185',
    '#fbbf24', '#fbbf24', '#fbbf24',
    '#818cf8', '#818cf8', '#818cf8', '#818cf8',
  ];

  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">
          One file was read <span className="text-rose">80 times</span> in a single session.
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          The AI forgets file contents between turns. When it needs information again,
          it re-reads the same file — even if nothing changed. That's {totalWasted.toLocaleString()} wasted reads
          across {repeatedReads.data.length} file-session pairs.
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-3 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-5 lg:col-span-2"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
            Top 10 Most Re-Read Files (in a single session)
          </h3>
          <ResponsiveContainer width="100%" height={360}>
            <BarChart data={top10} layout="vertical" margin={{ left: 0, right: 20 }}>
              <XAxis type="number" tick={{ fontSize: 10 }} />
              <YAxis
                type="category"
                dataKey="file"
                width={180}
                tick={{ fontSize: 11 }}
              />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="reads" radius={[0, 4, 4, 0]}>
                {top10.map((_: any, i: number) => (
                  <Cell key={i} fill={colors[i] || '#818cf8'} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </motion.div>

        {/* Impact callout */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2, duration: 0.5 }}
          className="flex flex-col gap-4"
        >
          <div className="bg-rose/5 border border-rose/20 rounded-xl p-5 flex-1">
            <RefreshCw size={20} className="text-rose mb-3" />
            <div className="text-3xl font-bold text-rose mb-1">{totalWasted.toLocaleString()}</div>
            <div className="text-sm text-text-2 mb-3">wasted file reads</div>
            <p className="text-xs text-text-3 leading-relaxed">
              If each Read call costs ~500 tokens of context, that's roughly{' '}
              <span className="text-text-1 font-semibold">{(totalWasted * 500).toLocaleString()}</span>{' '}
              tokens spent re-reading unchanged files.
            </p>
          </div>

          <div className="bg-surface-1 border border-border-dim rounded-xl p-5">
            <h4 className="text-xs font-medium text-text-3 uppercase tracking-wider mb-3">The fix</h4>
            <p className="text-sm text-text-2 leading-relaxed">
              Pre-loading frequently accessed files into the agent's context window would eliminate
              most of these redundant reads. The top 10 files alone account for{' '}
              <span className="text-text-1 font-semibold">
                {top10.reduce((s: number, d: any) => s + d.reads, 0)}
              </span>{' '}
              reads.
            </p>
          </div>
        </motion.div>
      </div>
    </section>
  );
}
