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

interface ChartData {
  intent_distribution: Record<string, number>;
  intent_by_developer: Record<string, Record<string, number>>;
  duration_breakdown: Record<string, number>;
}

const INTENT_COLORS: Record<string, string> = {
  understand: '#818cf8',
  build_feature: '#34d399',
  fix_bug: '#fb7185',
  config: '#fbbf24',
  deploy: '#22d3ee',
  test: '#a78bfa',
  refactor: '#f472b6',
  other: '#63637a',
};

const INTENT_LABELS: Record<string, string> = {
  understand: 'Understand Code',
  build_feature: 'Build Features',
  fix_bug: 'Fix Bugs',
  config: 'Configuration',
  deploy: 'Deploy',
  test: 'Testing',
  refactor: 'Refactor',
  other: 'Other',
};

const DURATION_COLORS = ['#63637a', '#818cf8', '#34d399', '#fb7185'];

function shortEmail(email: string): string {
  const at = email.indexOf('@');
  return at > 0 ? email.slice(0, at) : email;
}

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">
      <div className="text-text-2 mb-1">{d?.label || d?.name}</div>
      <div className="text-text-1 font-semibold">{d?.value?.toLocaleString()} prompts</div>
    </div>
  );
};

export default function IntentDistribution() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {
    intent_distribution: {},
    intent_by_developer: {},
    duration_breakdown: {},
  });

  const { intentData, totalPrompts, topIntent, devIntentData, durationData, totalSessions } = useMemo(() => {
    const intentData = Object.entries(data.intent_distribution || {})
      .filter(([k]) => k !== 'other')
      .map(([name, value]) => ({
        name,
        label: INTENT_LABELS[name] || name,
        value,
      }))
      .sort((a, b) => b.value - a.value);

    const totalPrompts = Object.values(data.intent_distribution || {}).reduce((s, v) => s + v, 0);
    const topIntent = intentData[0];

    // Per-developer breakdown for top 5 devs
    const devIntentData = Object.entries(data.intent_by_developer || {})
      .map(([email, intents]) => {
        const total = Object.values(intents).reduce((s, v) => s + v, 0);
        return {
          name: shortEmail(email),
          email,
          total,
          ...Object.fromEntries(
            Object.entries(intents).filter(([k]) => k !== 'other')
          ),
        };
      })
      .sort((a, b) => b.total - a.total)
      .slice(0, 6);

    const durationData = Object.entries(data.duration_breakdown || {}).map(([name, value]) => ({
      name,
      value,
    }));
    const totalSessions = durationData.reduce((s, d) => s + d.value, 0);

    return { intentData, totalPrompts, topIntent, devIntentData, durationData, totalSessions };
  }, [data]);

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

  const understandPct = topIntent
    ? ((topIntent.value / totalPrompts) * 100).toFixed(0)
    : '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">
          {understandPct}% of prompts are just trying to <span className="text-accent">understand</span> existing code.
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          Your team asks AI to explain code more than to write it. Building features is only the
          second most common intent. This confirms the AI is a comprehension tool first, a code generator second.
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Intent 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"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
            What Developers Ask AI to Do
          </h3>
          <ResponsiveContainer width="100%" height={280}>
            <BarChart data={intentData} layout="vertical" margin={{ left: 10, right: 20 }}>
              <XAxis type="number" hide />
              <YAxis type="category" dataKey="label" width={100} tick={{ fontSize: 11 }} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="value" radius={[0, 4, 4, 0]}>
                {intentData.map((d) => (
                  <Cell key={d.name} fill={INTENT_COLORS[d.name] || '#63637a'} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
          <div className="text-[10px] text-text-3 mt-2 text-center">
            {totalPrompts.toLocaleString()} total prompts classified by keyword intent
          </div>
        </motion.div>

        {/* Per-developer intent stacked */}
        <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">
            Intent by Developer
          </h3>
          <ResponsiveContainer width="100%" height={280}>
            <BarChart data={devIntentData} layout="vertical" margin={{ left: 10, right: 10 }}>
              <XAxis type="number" hide />
              <YAxis type="category" dataKey="name" width={100} tick={{ fontSize: 11 }} />
              <Tooltip />
              {Object.keys(INTENT_COLORS).filter(k => k !== 'other').map(intent => (
                <Bar
                  key={intent}
                  dataKey={intent}
                  stackId="intent"
                  fill={INTENT_COLORS[intent]}
                  radius={0}
                />
              ))}
            </BarChart>
          </ResponsiveContainer>
          <div className="flex flex-wrap gap-2 mt-2 justify-center">
            {Object.entries(INTENT_COLORS).filter(([k]) => k !== 'other').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 }} />
                {INTENT_LABELS[k] || k}
              </div>
            ))}
          </div>
        </motion.div>

        {/* Duration breakdown donut */}
        <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">
            Session Duration Breakdown
          </h3>
          <ResponsiveContainer width="100%" height={220}>
            <PieChart>
              <Pie
                data={durationData}
                dataKey="value"
                nameKey="name"
                cx="50%"
                cy="50%"
                innerRadius={50}
                outerRadius={85}
                paddingAngle={3}
                strokeWidth={0}
              >
                {durationData.map((_, i) => (
                  <Cell key={i} fill={DURATION_COLORS[i % DURATION_COLORS.length]} />
                ))}
              </Pie>
              <Tooltip />
            </PieChart>
          </ResponsiveContainer>
          {/* Center label */}
          <div className="text-center -mt-2 mb-2">
            <div className="text-2xl font-bold text-text-1">{totalSessions}</div>
            <div className="text-[10px] text-text-3">sessions</div>
          </div>
          <div className="space-y-1.5">
            {durationData.map((d, i) => (
              <div key={d.name} className="flex items-center justify-between text-xs">
                <div className="flex items-center gap-1.5">
                  <div className="w-2.5 h-2.5 rounded-full" style={{ background: DURATION_COLORS[i % DURATION_COLORS.length] }} />
                  <span className="text-text-2">{d.name}</span>
                </div>
                <span className="text-text-1 font-medium">
                  {d.value} <span className="text-text-3">({((d.value / totalSessions) * 100).toFixed(0)}%)</span>
                </span>
              </div>
            ))}
          </div>
        </motion.div>
      </div>
    </section>
  );
}
