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

interface RepoEntry {
  repo: string;
  sessions: number;
  developers: number;
  cost_usd: number;
  pct_of_total: number;
}

interface ChartData {
  repo_costs?: {
    headline: string;
    repos: RepoEntry[];
  };
}

const COLORS = ['#fb7185', '#818cf8', '#34d399', '#fbbf24', '#22d3ee', '#a78bfa', '#63637a'];

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-1 font-semibold mb-1">{d.repo}</div>
      <div className="text-text-2">${d.cost_usd.toFixed(0)} ({d.pct_of_total.toFixed(1)}%)</div>
      <div className="text-text-3">{d.sessions} sessions, {d.developers} dev{d.developers > 1 ? 's' : ''}</div>
    </div>
  );
};

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

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

  const { headline, repos } = data.repo_costs;
  const top = repos[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">
          One repo consumes <span className="text-rose">{top.pct_of_total.toFixed(0)}%</span> of total AI spend.
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          {headline}. {top.repo} alone costs ${top.cost_usd.toFixed(0)}<CostInfoTip /> with {top.sessions} sessions from {top.developers} developer{top.developers > 1 ? 's' : ''}.
        </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"
      >
        <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">Cost by Repository</h3>
        <ResponsiveContainer width="100%" height={Math.max(200, repos.length * 50)}>
          <BarChart data={repos} layout="vertical" margin={{ left: 20, right: 40 }}>
            <XAxis type="number" hide />
            <YAxis
              type="category"
              dataKey="repo"
              width={180}
              tick={{ fontSize: 11 }}
              tickFormatter={(v: string) => v.length > 25 ? '...' + v.slice(-22) : v}
            />
            <Tooltip content={<CustomTooltip />} />
            <Bar dataKey="cost_usd" radius={[0, 4, 4, 0]}>
              {repos.map((_: RepoEntry, i: number) => (
                <Cell key={i} fill={COLORS[i % COLORS.length]} />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>

        {/* Percentage bars below */}
        <div className="mt-6 space-y-2">
          {repos.slice(0, 5).map((r, i) => (
            <div key={r.repo} className="flex items-center gap-3">
              <div className="w-40 text-xs text-text-2 truncate">{r.repo.split('/').pop()}</div>
              <div className="flex-1 h-3 bg-surface-2 rounded-full overflow-hidden">
                <motion.div
                  initial={{ width: 0 }}
                  whileInView={{ width: `${r.pct_of_total}%` }}
                  viewport={{ once: true }}
                  transition={{ delay: 0.2 + i * 0.1, duration: 0.6 }}
                  className="h-full rounded-full"
                  style={{ background: COLORS[i % COLORS.length] }}
                />
              </div>
              <span className="text-xs text-text-3 w-16 text-right">${r.cost_usd.toFixed(0)}</span>
            </div>
          ))}
        </div>
      </motion.div>
    </section>
  );
}
