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 ExpensiveSession {
  session_id: string;
  email: string;
  source: string;
  repo: string;
  cost_usd: number;
  duration_min: number;
  input_tokens: number;
}

interface TokenWasteDev {
  email: string;
  no_edit_sessions: number;
  no_edit_cost: number;
  edit_sessions: number;
  edit_cost: number;
  waste_pct: number;
}

interface ChartData {
  cost_concentration?: {
    top_10_pct: number;
    top_10_cost: number;
    total_cost: number;
    total_sessions: number;
    headline: string;
    most_expensive_sessions: ExpensiveSession[];
  };
  token_waste?: {
    sessions_without_edits: { count: number; total_cost_usd: number; pct_of_total_cost: number; avg_cost_per_session?: number };
    sessions_with_edits: { count: number; total_cost_usd: number; pct_of_total_cost: number; avg_cost_per_session?: number };
    by_developer: TokenWasteDev[];
  };
}

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

function shortId(id: string): string {
  return id.slice(0, 8);
}

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 mb-1">{d?.name || d?.label}</div>
      <div className="text-text-1 font-semibold">${payload[0]?.value?.toFixed(2)}</div>
      {d?.source && <div className="text-text-3">{d.source} · {d.duration}</div>}
    </div>
  );
};

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

  const cc = data.cost_concentration;
  const tw = data.token_waste;

  if (loading || (!cc && !tw)) return null;

  const topSessions = (cc?.most_expensive_sessions || []).slice(0, 8).map(s => ({
    name: `${shortEmail(s.email)} · ${shortId(s.session_id)}`,
    label: `${shortEmail(s.email)} · ${s.repo?.split('/').pop()} · ${s.source}`,
    cost: s.cost_usd,
    source: s.source.replace('_', ' '),
    duration: s.duration_min < 1 ? '<1 min' : `${Math.round(s.duration_min)} min`,
  }));

  const wasteByDev = (tw?.by_developer || []).map(d => ({
    name: shortEmail(d.email),
    noEditCost: d.no_edit_cost,
    editCost: d.edit_cost,
    wastePct: d.waste_pct,
  }));

  return (
    <section className="px-8 max-w-7xl mx-auto py-20">
      {cc && (
        <>
          <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-rose">10 sessions</span> consumed {cc.top_10_pct.toFixed(0)}% of total AI spend.
            </h2>
            <p className="text-text-2 mb-10 max-w-2xl">
              ${Math.round(cc.top_10_cost).toLocaleString()} out of ${Math.round(cc.total_cost).toLocaleString()} total spend<CostInfoTip />
              came from just 10 sessions out of {cc.total_sessions}. The most expensive single session cost ${topSessions[0]?.cost.toFixed(2)} — and lasted {topSessions[0]?.duration}.
            </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-5 mb-6"
          >
            <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
              Most Expensive Sessions
            </h3>
            <ResponsiveContainer width="100%" height={Math.max(200, topSessions.length * 40)}>
              <BarChart data={topSessions} layout="vertical" margin={{ left: 10, right: 40 }}>
                <XAxis type="number" tick={{ fontSize: 10 }} tickFormatter={(v) => `$${v}`} />
                <YAxis type="category" dataKey="name" width={180} tick={{ fontSize: 10, fontFamily: 'monospace' }} />
                <Tooltip content={<CustomTooltip />} />
                <Bar dataKey="cost" radius={[0, 4, 4, 0]}>
                  {topSessions.map((_, i) => (
                    <Cell key={i} fill={i === 0 ? '#fb7185' : i < 3 ? '#fbbf24' : '#818cf8'} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </motion.div>
        </>
      )}

      {tw && wasteByDev.length > 0 && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2, duration: 0.5 }}
          className="grid grid-cols-1 lg:grid-cols-2 gap-6"
        >
          {/* Token waste stats */}
          <div className="bg-rose/5 border border-rose/20 rounded-xl p-5">
            <h3 className="text-sm font-medium text-rose uppercase tracking-wider mb-4">
              Sessions Without Edits = {tw.sessions_without_edits.pct_of_total_cost.toFixed(1)}% of Spend
            </h3>
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div className="bg-surface-1 rounded-lg p-4 text-center">
                <div className="text-2xl font-black text-rose">${Math.round(tw.sessions_without_edits.total_cost_usd).toLocaleString()}</div>
                <div className="text-xs text-text-3 mt-1">{tw.sessions_without_edits.count} sessions with no edits</div>
              </div>
              <div className="bg-surface-1 rounded-lg p-4 text-center">
                <div className="text-2xl font-black text-green">${tw.sessions_with_edits.total_cost_usd.toFixed(2)}</div>
                <div className="text-xs text-text-3 mt-1">{tw.sessions_with_edits.count} sessions with edits</div>
              </div>
            </div>
            <div className="text-xs text-text-3 leading-relaxed">
              Sessions that produced code edits cost ${tw.sessions_with_edits.avg_cost_per_session?.toFixed(2) ?? '0.05'}/session on average.
              Sessions without edits cost ${tw.sessions_without_edits.avg_cost_per_session?.toFixed(2) ?? '6.43'}/session — 100x more.
              This doesn't mean all no-edit sessions are waste, but the cost disparity is extreme.
            </div>
          </div>

          {/* Per-developer waste breakdown */}
          <div 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">
              Cost Split: Edits vs No Edits by Developer
            </h3>
            <ResponsiveContainer width="100%" height={Math.max(160, wasteByDev.length * 50)}>
              <BarChart data={wasteByDev} layout="vertical" margin={{ left: 10, right: 30 }}>
                <XAxis type="number" tick={{ fontSize: 10 }} tickFormatter={(v) => `$${v}`} />
                <YAxis type="category" dataKey="name" width={120} tick={{ fontSize: 11 }} />
                <Tooltip contentStyle={{ background: '#1a1a2e', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, color: '#e2e8f0' }} itemStyle={{ color: '#e2e8f0' }} />
                <Bar dataKey="noEditCost" name="No-edit sessions" fill="#fb7185" stackId="a" radius={[0, 0, 0, 0]} />
                <Bar dataKey="editCost" name="Edit sessions" fill="#34d399" stackId="a" radius={[0, 4, 4, 0]} />
              </BarChart>
            </ResponsiveContainer>
            <div className="flex gap-4 justify-center mt-3 text-xs text-text-3">
              <div className="flex items-center gap-1.5">
                <div className="w-2.5 h-2.5 rounded-sm" style={{ background: '#fb7185' }} />
                No-edit sessions
              </div>
              <div className="flex items-center gap-1.5">
                <div className="w-2.5 h-2.5 rounded-sm" style={{ background: '#34d399' }} />
                Edit sessions
              </div>
            </div>
          </div>
        </motion.div>
      )}
    </section>
  );
}
