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

interface ChartData {
  tool_category_distribution: Record<string, number>;
  sessions_by_source: Record<string, number>;
  sessions_by_hour: Record<string, number>;
}

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

const SOURCE_COLORS: Record<string, string> = {
  claude_code: '#818cf8',
  codex_cli: '#34d399',
  gemini_cli: '#22d3ee',
  cursor: '#fbbf24',
  test: '#63637a',
  qc_trace_install: '#63637a',
};

const CustomTooltip = ({ active, payload, label }: any) => {
  if (!active || !payload?.length) return null;
  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">{label || payload[0]?.name}</div>
      <div className="text-text-1 font-semibold">{payload[0]?.value?.toLocaleString()}</div>
    </div>
  );
};

export default function ToolBreakdown() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {
    tool_category_distribution: {},
    sessions_by_source: {},
    sessions_by_hour: {},
  });
  const { tz, formatHour, offsetHour } = useTimezone();

  if (loading) return null;

  const catData = Object.entries(data.tool_category_distribution)
    .map(([name, value]) => ({ name, value }))
    .sort((a, b) => b.value - a.value);

  const total = catData.reduce((s, d) => s + d.value, 0);

  const sourceData = Object.entries(data.sessions_by_source)
    .filter(([k]) => !['test', 'qc_trace_install'].includes(k))
    .map(([name, value]) => ({ name: name.replace('_', ' '), value, key: name }));

  const hourData = Object.entries(data.sessions_by_hour)
    .map(([h, v]) => ({ hour: formatHour(Number(h)), value: v, h: offsetHour(Number(h)) }))
    .sort((a, b) => a.h - b.h);

  const exploreP = ((data.tool_category_distribution.explore || 0) / total * 100).toFixed(0);
  const editP = ((data.tool_category_distribution.edit || 0) / total * 100).toFixed(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">
          Your AI spends <span className="text-accent">{exploreP}%</span> of its time reading
          and only <span className="text-green">{editP}%</span> writing.
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          For every file edited, the AI reads nearly 2 files first. That's exploration overhead —
          time spent understanding code before it can change it.
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Tool categories */}
        <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 col-span-1"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">How AI Spends Its Time</h3>
          <ResponsiveContainer width="100%" height={280}>
            <BarChart data={catData} layout="vertical" margin={{ left: 10, right: 20 }}>
              <XAxis type="number" hide />
              <YAxis type="category" dataKey="name" width={70} tick={{ fontSize: 12 }} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="value" radius={[0, 4, 4, 0]}>
                {catData.map((d) => (
                  <Cell key={d.name} fill={COLORS[d.name] || '#63637a'} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </motion.div>

        {/* Source distribution */}
        <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 col-span-1"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">Sessions by CLI Tool</h3>
          <ResponsiveContainer width="100%" height={280}>
            <PieChart>
              <Pie
                data={sourceData}
                dataKey="value"
                nameKey="name"
                cx="50%"
                cy="50%"
                innerRadius={55}
                outerRadius={90}
                paddingAngle={3}
                strokeWidth={0}
              >
                {sourceData.map((d) => (
                  <Cell key={d.key} fill={SOURCE_COLORS[d.key] || '#63637a'} />
                ))}
              </Pie>
              <Tooltip content={<CustomTooltip />} />
            </PieChart>
          </ResponsiveContainer>
          <div className="text-center -mt-1 mb-2">
            <div className="text-xl font-bold text-text-1">{sourceData.reduce((s, d) => s + d.value, 0)}</div>
            <div className="text-[10px] text-text-3">sessions</div>
          </div>
          <div className="flex flex-wrap gap-3 justify-center">
            {sourceData.map(d => (
              <div key={d.key} className="flex items-center gap-1.5 text-xs text-text-2">
                <div className="w-2.5 h-2.5 rounded-full" style={{ background: SOURCE_COLORS[d.key] || '#63637a' }} />
                {d.name} ({d.value})
              </div>
            ))}
          </div>
        </motion.div>

        {/* Hourly activity */}
        <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 col-span-1"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">When Developers Code ({tz})</h3>
          <ResponsiveContainer width="100%" height={240}>
            <BarChart data={hourData} margin={{ bottom: 0 }}>
              <XAxis dataKey="hour" tick={{ fontSize: 10 }} interval={1} />
              <YAxis hide />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="value" fill="#818cf8" radius={[3, 3, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
          {(() => {
            const peak = hourData.reduce((best, h) => h.value > best.value ? h : best, hourData[0]);
            return (
              <div className="mt-3 bg-accent/5 border border-accent/20 rounded-lg p-3 text-xs text-text-2">
                <span className="font-semibold text-accent">Peak hour:</span>{' '}
                {peak?.hour} {tz} with {peak?.value} sessions.
              </div>
            );
          })()}
        </motion.div>
      </div>
    </section>
  );
}
