import { useMemo } from 'react';
import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';

interface ToolInfo {
  tool_name: string;
  call_count: number;
  session_count: number;
  category: string;
}

interface ToolAnalysis {
  frequency: ToolInfo[];
  top_edited_files: Record<string, number>;
  top_read_files: Record<string, number>;
}

const CATEGORY_COLORS: Record<string, string> = {
  explore: '#818cf8',
  shell: '#22d3ee',
  edit: '#34d399',
  planning: '#fbbf24',
  other: '#63637a',
  web: '#fb7185',
  delegation: '#a78bfa',
};

export default function ToolFrequency() {
  const { data, loading } = useData<ToolAnalysis>('/data/tool_analysis.json', {
    frequency: [],
    top_edited_files: {},
    top_read_files: {},
  });

  const { tools, maxCount, topEdited, topRead } = useMemo(() => {
    const tools = (data.frequency || []).filter(t => t.call_count > 10).slice(0, 20);
    const maxCount = tools[0]?.call_count || 1;

    const topEdited = Object.entries(data.top_edited_files || {})
      .slice(0, 10)
      .map(([path, count]) => ({ path, count, name: path.split('/').pop() || path }));

    const topRead = Object.entries(data.top_read_files || {})
      .slice(0, 10)
      .map(([path, count]) => ({ path, count, name: path.split('/').pop() || path }));

    return { tools, maxCount, topEdited, topRead };
  }, [data]);

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

  const totalCalls = tools.reduce((s, t) => s + t.call_count, 0);

  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">
          <span className="text-accent">Read</span> is king — {((tools.find(t => t.tool_name === 'Read')?.call_count || 0) / totalCalls * 100).toFixed(0)}% of all tool calls.
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          The AI's most-used ability is reading files. Here's every tool it called,
          ranked by frequency, alongside the files it touched most.
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Tool frequency bars */}
        <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-1"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
            Tool Call Frequency
          </h3>
          <div className="space-y-1.5">
            {tools.map((t, i) => {
              const pct = (t.call_count / maxCount) * 100;
              const color = CATEGORY_COLORS[t.category] || '#63637a';
              return (
                <motion.div
                  key={t.tool_name}
                  initial={{ opacity: 0, x: -10 }}
                  whileInView={{ opacity: 1, x: 0 }}
                  viewport={{ once: true }}
                  transition={{ delay: i * 0.02, duration: 0.3 }}
                  className="flex items-center gap-2 group"
                >
                  <div className="w-28 text-right text-[11px] font-medium text-text-2 truncate shrink-0">
                    {t.tool_name}
                  </div>
                  <div className="flex-1 h-5 bg-surface-2 rounded-sm overflow-hidden relative">
                    <motion.div
                      initial={{ width: 0 }}
                      whileInView={{ width: `${pct}%` }}
                      viewport={{ once: true }}
                      transition={{ delay: 0.1 + i * 0.02, duration: 0.5 }}
                      className="h-full rounded-sm"
                      style={{ background: `${color}88` }}
                    />
                  </div>
                  <div className="w-12 text-right text-[10px] text-text-3 tabular-nums shrink-0">
                    {t.call_count.toLocaleString()}
                  </div>
                </motion.div>
              );
            })}
          </div>
          {/* Category legend */}
          <div className="flex flex-wrap gap-2 mt-4 pt-3 border-t border-border-dim">
            {Object.entries(CATEGORY_COLORS).map(([k, c]) => (
              <div key={k} className="flex items-center gap-1 text-[10px] text-text-3">
                <div className="w-2 h-2 rounded-sm" style={{ background: c }} />
                {k}
              </div>
            ))}
          </div>
        </motion.div>

        {/* Most edited files */}
        <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">
            Most Edited Files
          </h3>
          {topEdited.length > 0 ? (
            <div className="space-y-2">
              {topEdited.map((f) => {
                const maxE = topEdited[0]?.count || 1;
                return (
                  <div key={f.path} className="flex items-center gap-2">
                    <div className="w-7 text-right text-xs font-bold text-green tabular-nums">{f.count}</div>
                    <div className="flex-1 h-5 bg-surface-2 rounded-sm overflow-hidden relative">
                      <div
                        className="h-full rounded-sm bg-green/30"
                        style={{ width: `${(f.count / maxE) * 100}%` }}
                      />
                      <span className="absolute inset-0 flex items-center px-2 text-[10px] text-text-2 truncate">
                        {f.name}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="text-xs text-text-3">No data available</div>
          )}
        </motion.div>

        {/* Most read files */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.3, 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">
            Most Read Files
          </h3>
          {topRead.length > 0 ? (
            <div className="space-y-2">
              {topRead.map((f) => {
                const maxR = topRead[0]?.count || 1;
                return (
                  <div key={f.path} className="flex items-center gap-2">
                    <div className="w-7 text-right text-xs font-bold text-accent tabular-nums">{f.count}</div>
                    <div className="flex-1 h-5 bg-surface-2 rounded-sm overflow-hidden relative">
                      <div
                        className="h-full rounded-sm bg-accent/30"
                        style={{ width: `${(f.count / maxR) * 100}%` }}
                      />
                      <span className="absolute inset-0 flex items-center px-2 text-[10px] text-text-2 truncate">
                        {f.name}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="text-xs text-text-3">No data available</div>
          )}
        </motion.div>
      </div>
    </section>
  );
}
