import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, Cell, Legend, 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";
import type { DerivedMetrics } from "../../lib/deriveMetrics";

const COLORS = ["#4f46e5", "#16a34a", "#d97706", "#7c3aed"];
const DEV_COLORS = ["#4f46e5", "#16a34a", "#d97706"];
const tooltipStyle = { borderRadius: 6, border: "1px solid #e2e8f0", boxShadow: "0 2px 8px rgba(0,0,0,0.06)", fontSize: 12, padding: "6px 10px" };

interface Props { data: AllData; derived: DerivedMetrics }

export function ProductivitySection({ data, derived }: Props) {
  const { mode } = useViewMode();
  const a04 = data.a04_session_outcomes;
  const p = data.c01_developer_profile.profile;
  const pct = (n: number) => `${(n * 100).toFixed(1)}%`;
  const total = a04.total_sessions;

  const barData = [
    { name: "Edit", count: a04.sessions_with_edits, pct: total > 0 ? +((a04.sessions_with_edits / total) * 100).toFixed(1) : 0 },
    { name: "Commit", count: a04.sessions_with_commits, pct: total > 0 ? +((a04.sessions_with_commits / total) * 100).toFixed(1) : 0 },
    { name: "Test", count: a04.sessions_with_tests, pct: total > 0 ? +((a04.sessions_with_tests / total) * 100).toFixed(1) : 0 },
    { name: "Push", count: a04.per_session.filter((s) => s.has_git_push).length, pct: total > 0 ? +((a04.per_session.filter((s) => s.has_git_push).length / total) * 100).toFixed(1) : 0 },
  ].map(d => ({ ...d, topLabel: `${d.count} (${d.pct}%)` }));

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const sessions = a04.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 dt = ds.length;
    return {
      name: dev,
      editPct: dt > 0 ? +((ds.filter((s: { has_edits: boolean }) => s.has_edits).length / dt) * 100).toFixed(1) : 0,
      commitPct: dt > 0 ? +((ds.filter((s: { has_git_commit: boolean }) => s.has_git_commit).length / dt) * 100).toFixed(1) : 0,
      testPct: dt > 0 ? +((ds.filter((s: { has_test_run: boolean }) => s.has_test_run).length / dt) * 100).toFixed(1) : 0,
    };
  });

  return (
    <Section id="productivity" title="Productivity" subtitle="Code output and git operations">
      <MetricStrip metrics={[
        { label: "Edit Sessions", value: pct(p.edit_session_pct), accent: "blue", hint: "% of sessions that modified files" },
        { label: "Commit Sessions", value: pct(p.commit_session_pct), accent: "green", hint: "% of sessions with git commits" },
        { label: "Test Sessions", value: `${a04.sessions_with_tests}`, sub: `of ${total}`, accent: "amber", hint: "Sessions that ran test suites" },
        { label: "Pass After Fail", value: a04.per_session.filter((s) => s.has_test_pass_after_fail).length, accent: "purple", hint: "Tests fixed within same session" },
      ]} />

      <div className="mt-3">
        <MetricStrip metrics={[
          { label: "Sessions with Edits", value: a04.sessions_with_edits, accent: "green", hint: "Productive sessions that changed code" },
          { label: "Zero-Edit Sessions", value: `${derived.zeroEditCount} (~$${derived.zeroEditEstimatedCost.toFixed(0)})`, accent: "red", hint: "Sessions that cost money but produced no code changes" },
        ]} />
      </div>

      <div className={`grid ${mode === "dev" ? "md:grid-cols-2" : ""} gap-3 mt-4`}>
        <ChartCard title="Session Outcomes" description="How many sessions resulted in each action">
          <ResponsiveContainer debounce={0} width="100%" height={280}>
            <BarChart data={barData} barSize={44} barGap={8} margin={{ top: 30 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" vertical={false} />
              <XAxis dataKey="name" tick={{ fontSize: 12, fill: "#334155", fontWeight: 500 }} axisLine={false} tickLine={false} dy={6} />
              <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="topLabel" position="top" fontSize={10} fill="#475569" fontWeight={500} />
                {barData.map((_, i) => <Cell key={i} fill={COLORS[i]} />)}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>

        {mode === "dev" && devCompare.length > 0 && (
          <ChartCard title="Productivity by Developer" description="% of sessions with edits, commits, or tests">
            <ResponsiveContainer debounce={0} width="100%" height={280}>
              <BarChart data={devCompare} barSize={18} barGap={2} margin={{ top: 24 }}>
                <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="%" />
                <Tooltip contentStyle={tooltipStyle} cursor={false} />
                <Legend verticalAlign="top" height={26} wrapperStyle={{ fontSize: 11 }} />
                <Bar isAnimationActive={false} dataKey="editPct" name="Edit %" fill={DEV_COLORS[0]} radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="editPct" position="top" fontSize={9} fill="#64748b" formatter={(v) => `${v}%`} />
                </Bar>
                <Bar isAnimationActive={false} dataKey="commitPct" name="Commit %" fill={DEV_COLORS[1]} radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="commitPct" position="top" fontSize={9} fill="#64748b" formatter={(v) => `${v}%`} />
                </Bar>
                <Bar isAnimationActive={false} dataKey="testPct" name="Test %" fill={DEV_COLORS[2]} radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="testPct" position="top" fontSize={9} fill="#64748b" formatter={(v) => `${v}%`} />
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ChartCard>
        )}
      </div>
    </Section>
  );
}
