import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, Cell, LabelList } from "recharts";
import { MetricStrip } from "../../components/MetricStrip";
import { ChartCard } from "../../components/ChartCard";
import { Section } from "../../components/Section";
import { useViewMode } from "../../context/ViewModeContext";
import type { AllData } from "../../types/data";

const DEV_COLORS = ["#4f46e5", "#16a34a", "#d97706", "#7c3aed", "#0891b2"];
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 AiEffectivenessSection({ data }: { data: AllData }) {
  const { mode } = useViewMode();
  const a01 = data.a01_interruptions;
  const a10 = data.a10_error_detection;
  const p = data.c01_developer_profile.profile;
  const pct = (n: number) => `${(n * 100).toFixed(1)}%`;

  const recoveredCount = a01.per_session.filter((s) => s.session_recovered).length;
  const recoveryRate = a01.sessions_with_interrupts > 0 ? recoveredCount / a01.sessions_with_interrupts : 0;
  const cascadeRate = a10.total_sessions > 0 ? a10.sessions_with_cascades / a10.total_sessions : 0;

  const cleanCount = a01.total_sessions - a01.sessions_with_interrupts;
  const cleanPct = a01.total_sessions > 0 ? ((cleanCount / a01.total_sessions) * 100).toFixed(0) : "0";
  const intPct = a01.total_sessions > 0 ? ((a01.sessions_with_interrupts / a01.total_sessions) * 100).toFixed(0) : "0";

  const BUCKET_META: Record<string, { label: string; desc: string; color: string }> = {
    mostly_early: { label: "Early (0-30%)", desc: "Likely wrong direction", color: "#dc2626" },
    mid_session: { label: "Mid (30-70%)", desc: "AI got stuck or off-track", color: "#d97706" },
    mostly_late: { label: "Late (70-100%)", desc: "Minor corrections", color: "#16a34a" },
    spread: { label: "Spread Out", desc: "Ongoing collaboration", color: "#7c3aed" },
  };
  const buckets: Record<string, { count: number; desc: string; color: string }> = {};
  for (const s of a01.per_session) {
    if (s.interrupt_position_bucket) {
      const meta = BUCKET_META[s.interrupt_position_bucket] ?? { label: s.interrupt_position_bucket, desc: "", color: "#94a3b8" };
      const label = meta.label;
      if (!buckets[label]) buckets[label] = { count: 0, desc: meta.desc, color: meta.color };
      buckets[label].count++;
    }
  }
  const bucketTotal = Object.values(buckets).reduce((s, b) => s + b.count, 0);
  const bucketData = Object.entries(buckets)
    .map(([name, { count, desc, color }]) => ({ name, count, desc, color, barLabel: `${count} (${bucketTotal > 0 ? ((count / bucketTotal) * 100).toFixed(0) : 0}%)` }))
    .sort((a, b) => b.count - a.count);

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const sessions = a01.per_session as any[];
  const devNames = [...new Set(sessions.map((s: { developer?: string }) => s.developer).filter(Boolean))] as string[];
  const devCompare = devNames.map((dev) => {
    const ds = sessions.filter((s: { developer?: string }) => s.developer === dev);
    const interrupted = ds.filter((s: { interrupt_count: number }) => s.interrupt_count > 0).length;
    const total = ds.length;
    return {
      name: dev,
      interruptRate: total > 0 ? +((interrupted / total) * 100).toFixed(1) : 0,
      barLabel: total > 0 ? `${((interrupted / total) * 100).toFixed(0)}%` : "0%",
    };
  });

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const errSessions = data.a10_error_detection.per_session as any[];
  const errBuckets = [
    { name: "No errors", count: errSessions.filter((s: { shell_error_count: number }) => s.shell_error_count === 0).length },
    { name: "1-2 errors", count: errSessions.filter((s: { shell_error_count: number }) => s.shell_error_count >= 1 && s.shell_error_count <= 2).length },
    { name: "3-5 errors", count: errSessions.filter((s: { shell_error_count: number }) => s.shell_error_count >= 3 && s.shell_error_count <= 5).length },
    { name: "6+ errors", count: errSessions.filter((s: { shell_error_count: number }) => s.shell_error_count >= 6).length },
  ];
  const errTotal = errBuckets.reduce((s, d) => s + d.count, 0);
  const errData = errBuckets.map(d => ({ ...d, barLabel: `${d.count} (${errTotal > 0 ? ((d.count / errTotal) * 100).toFixed(0) : 0}%)` }));

  return (
    <Section id="ai-effectiveness" title="AI Effectiveness" subtitle="Autonomy, interruptions, and error handling">
      <MetricStrip metrics={[
        { label: "Autonomy Ratio", value: p.avg_autonomy_ratio.toFixed(1), accent: "blue", hint: "AI tool calls per user message" },
        { label: "Interrupt Rate", value: pct(p.interrupt_rate), accent: "red", hint: "Sessions where user had to intervene" },
        { label: "Recovery Rate", value: pct(recoveryRate), accent: "green", hint: "Interrupted sessions that still succeeded" },
        { label: "Cascade Rate", value: pct(cascadeRate), accent: "amber", hint: "Sessions with repeated sequential failures" },
        { label: "Undo Rate", value: pct(p.undo_rate), accent: "purple", hint: "Sessions where user requested undo/revert" },
      ]} />

      {/* Session quality summary */}
      <div className="grid grid-cols-2 gap-3 mt-4">
        <div className="bg-white rounded-lg border border-slate-200 p-5">
          <div className="flex items-center justify-between mb-2">
            <span className="text-[12px] font-medium text-slate-500">Clean Sessions</span>
            <span className="text-[11px] text-slate-400">AI completed without interruption</span>
          </div>
          <div className="flex items-end gap-2">
            <span className="text-[32px] font-bold text-slate-900 leading-none tabular-nums">{cleanCount}</span>
            <span className="text-[14px] text-slate-300 mb-0.5">/ {a01.total_sessions}</span>
          </div>
          <div className="mt-3 w-full bg-slate-100 rounded-full h-2">
            <div className="bg-slate-700 h-2 rounded-full transition-all" style={{ width: `${cleanPct}%` }} />
          </div>
          <p className="text-[11px] text-slate-500 mt-1.5 tabular-nums">{cleanPct}%</p>
        </div>

        <div className="bg-white rounded-lg border border-slate-200 p-5">
          <div className="flex items-center justify-between mb-2">
            <span className="text-[12px] font-medium text-slate-500">Interrupted Sessions</span>
            <span className="text-[11px] text-slate-400">User had to intervene</span>
          </div>
          <div className="flex items-end gap-2">
            <span className="text-[32px] font-bold text-slate-900 leading-none tabular-nums">{a01.sessions_with_interrupts}</span>
            <span className="text-[14px] text-slate-300 mb-0.5">/ {a01.total_sessions}</span>
          </div>
          <div className="mt-3 w-full bg-slate-100 rounded-full h-2">
            <div className="bg-red-500 h-2 rounded-full transition-all" style={{ width: `${intPct}%` }} />
          </div>
          <p className="text-[11px] text-slate-500 mt-1.5 tabular-nums">
            {intPct}%
            {recoveredCount > 0 && <span className="text-emerald-600 ml-2">{recoveredCount} recovered</span>}
          </p>
        </div>
      </div>

      {bucketData.length > 0 && (
        <div className="mt-4">
          <ChartCard title="Interrupt Timing" description="When in the session do interrupts happen">
            <ResponsiveContainer debounce={0} width="100%" height={220}>
              <BarChart data={bucketData} barSize={36} margin={{ top: 28 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 10, fill: "#334155", fontWeight: 500 }} axisLine={false} tickLine={false} />
                <YAxis tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false} domain={[0, (dataMax: number) => Math.ceil(dataMax * 1.2)]} />
                <Tooltip contentStyle={tooltipStyle} cursor={false} />
                <Bar isAnimationActive={false} dataKey="count" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="barLabel" position="top" fontSize={10} fill="#475569" fontWeight={500} />
                  {bucketData.map((d) => <Cell key={d.name} fill={d.color} />)}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ChartCard>
        </div>
      )}

      {mode === "dev" && (
        <div className="grid md:grid-cols-2 gap-3 mt-3">
          {devCompare.length > 0 && (
            <ChartCard title="Interrupt Rate by Developer">
              <ResponsiveContainer debounce={0} width="100%" height={240}>
                <BarChart data={devCompare} barSize={44} margin={{ top: 28 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" vertical={false} />
                  <XAxis dataKey="name" tick={{ fontSize: 11, fill: "#334155", fontWeight: 500 }} axisLine={false} tickLine={false} />
                  <YAxis tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false} unit="%" domain={[0, 'auto']} />
                  <Tooltip contentStyle={tooltipStyle} cursor={false} />
                  <Bar isAnimationActive={false} dataKey="interruptRate" name="Interrupt %" radius={[4, 4, 0, 0]}>
                    <LabelList dataKey="barLabel" position="top" fontSize={10} fill="#475569" fontWeight={500} />
                    {devCompare.map((_, i) => <Cell key={i} fill={DEV_COLORS[i]} />)}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </ChartCard>
          )}

          <ChartCard title="Error Distribution" description="Shell errors per session">
            <ResponsiveContainer debounce={0} width="100%" height={240}>
              <BarChart data={errData} barSize={36} margin={{ top: 28 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 10, fill: "#334155", fontWeight: 500 }} axisLine={false} tickLine={false} />
                <YAxis tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false} domain={[0, (dataMax: number) => Math.ceil(dataMax * 1.2)]} />
                <Tooltip contentStyle={tooltipStyle} cursor={false} />
                <Bar isAnimationActive={false} dataKey="count" fill="#dc2626" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="barLabel" position="top" fontSize={10} fill="#475569" fontWeight={500} />
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ChartCard>
        </div>
      )}
    </Section>
  );
}
