import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, Cell, LabelList } from "recharts";
import { ChartCard } from "../../components/ChartCard";
import { Section } from "../../components/Section";
import { useViewMode } from "../../context/ViewModeContext";
import type { DerivedMetrics, SessionArc } from "../../lib/deriveMetrics";

const ARC_META: Record<SessionArc, { label: string; color: string; desc: string }> = {
  full_cycle:        { label: "Full Cycle",      color: "#16a34a", desc: "Read, edited, then committed/tested/pushed" },
  explore_then_edit: { label: "Explore + Edit",  color: "#7c3aed", desc: "Browsed codebase first, then made edits" },
  explore_only:      { label: "Explore Only",    color: "#2563eb", desc: "Read files/searched code but changed nothing" },
  quick_lookup:      { label: "Quick Lookup",    color: "#0891b2", desc: "Brief session — quick question or check" },
  direct_edit:       { label: "Direct Edit",     color: "#4f46e5", desc: "Jumped straight to editing without exploring" },
  shell_only:        { label: "Shell Only",      color: "#d97706", desc: "Ran terminal commands only" },
  empty:             { label: "Empty",           color: "#94a3b8", desc: "No meaningful tool usage detected" },
};

const tooltipStyle = { borderRadius: 6, border: "1px solid #e2e8f0", boxShadow: "0 2px 8px rgba(0,0,0,0.06)", fontSize: 12, padding: "6px 10px" };

export function SessionArcsSection({ derived }: { derived: DerivedMetrics }) {
  const { mode } = useViewMode();
  const total = Object.values(derived.arcCounts).reduce((a, b) => a + b, 0);

  const arcData = (Object.entries(derived.arcCounts) as [SessionArc, number][])
    .filter(([, v]) => v > 0)
    .sort(([, a], [, b]) => b - a)
    .map(([arc, count]) => ({
      arc,
      count,
      pct: total > 0 ? +((count / total) * 100).toFixed(1) : 0,
      barLabel: `${count} (${total > 0 ? ((count / total) * 100).toFixed(0) : 0}%)`,
      ...ARC_META[arc],
    }));

  return (
    <Section id="session-arcs" title="Session Arcs" subtitle="What developers actually do in each session">
      <div className={`grid ${mode === "dev" ? "md:grid-cols-2" : ""} gap-3`}>
        <ChartCard title="Session Arc Breakdown" description="Ranked by frequency">
          <ResponsiveContainer debounce={0} width="100%" height={arcData.length * 48 + 30}>
            <BarChart data={arcData} layout="vertical" barSize={24} margin={{ left: 10, right: 80 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" horizontal={false} />
              <XAxis type="number" tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false} />
              <YAxis type="category" dataKey="label" tick={{ fontSize: 11, fill: "#334155", fontWeight: 500 }} axisLine={false} tickLine={false} width={110} />
              <Tooltip contentStyle={tooltipStyle} cursor={false} formatter={(value) => [`${Number(value ?? 0)} sessions`, ""]} />
              <Bar isAnimationActive={false} dataKey="count" radius={[0, 4, 4, 0]}>
                <LabelList dataKey="barLabel" position="right" fontSize={10} fill="#64748b" fontWeight={500} />
                {arcData.map((d) => <Cell key={d.arc} fill={d.color} />)}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>

        {mode === "dev" && (
          <ChartCard title="Arc Classification Reference" description="How each arc type is determined">
            <div className="space-y-2.5 py-1">
              {arcData.map((a) => (
                <div key={a.arc} className="flex items-start gap-2.5">
                  <span className="w-2.5 h-2.5 rounded-sm mt-0.5 shrink-0" style={{ backgroundColor: a.color }} />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between">
                      <span className="text-[12px] font-medium text-slate-700">{a.label}</span>
                      <span className="text-[11px] text-slate-400 tabular-nums">{a.count} ({a.pct}%)</span>
                    </div>
                    <p className="text-[11px] text-slate-400 leading-snug">{a.desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </ChartCard>
        )}
      </div>
    </Section>
  );
}
