import { Tooltip, ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, ScatterChart, Scatter, 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";

const COLORS = ["#2563eb", "#16a34a", "#d97706", "#dc2626", "#7c3aed"];
const DEV_COLORS: Record<string, string> = { zzjjaayy: "#4f46e5", ajay: "#16a34a", vaibhav: "#d97706" };
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 WorkflowPatternsSection({ data }: { data: AllData }) {
  const { mode } = useViewMode();
  const a07 = data.a07_conversation_dynamics;
  const a08 = data.a08_session_linkage;
  const c02 = data.c02_team_trends;
  const total = a08.total_sessions;

  const srcTotals: Record<string, number> = {};
  for (const w of c02.weeks) {
    for (const [src, count] of Object.entries(w.source_distribution)) {
      srcTotals[src] = (srcTotals[src] || 0) + count;
    }
  }
  const srcData = Object.entries(srcTotals).map(([name, value]) => ({ name: name.replace(/_/g, " "), value }));

  const durBuckets = { "<1m": 0, "1-5m": 0, "5-15m": 0, "15-60m": 0, ">60m": 0 };
  for (const s of a07.per_session) {
    const d = s.session_duration_min;
    if (d < 1) durBuckets["<1m"]++;
    else if (d < 5) durBuckets["1-5m"]++;
    else if (d < 15) durBuckets["5-15m"]++;
    else if (d < 60) durBuckets["15-60m"]++;
    else durBuckets[">60m"]++;
  }
  const durTotal = Object.values(durBuckets).reduce((a, b) => a + b, 0);
  const durData = Object.entries(durBuckets).map(([name, count]) => ({
    name, count, barLabel: `${count} (${durTotal > 0 ? ((count / durTotal) * 100).toFixed(0) : 0}%)`,
  }));

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const sessions = a07.per_session as any[];
  const devNames = [...new Set(sessions.map((s: { developer?: string }) => s.developer).filter(Boolean))] as string[];
  const scatterByDev = devNames.map((dev) => ({
    dev,
    data: sessions
      .filter((s: { developer?: string; session_duration_min: number; total_turns: number }) => s.developer === dev && s.session_duration_min > 0 && s.total_turns > 0)
      .map((s: { session_duration_min: number; total_turns: number }) => ({ x: +s.session_duration_min.toFixed(1), y: s.total_turns })),
  }));

  const fmtPct = (n: number) => total > 0 ? `${((n / total) * 100).toFixed(1)}%` : "0%";

  return (
    <Section id="workflow-patterns" title="Workflow Patterns" subtitle="Session structure and timing">
      <MetricStrip metrics={[
        { label: "Continuations", value: a08.continuation_sessions, sub: fmtPct(a08.continuation_sessions), accent: "blue", hint: "Sessions resuming previous work" },
        { label: "Parallel", value: a08.parallel_sessions, sub: fmtPct(a08.parallel_sessions), accent: "amber", hint: "Overlapping concurrent sessions" },
        { label: "Sequential", value: a08.sequential_sessions, sub: fmtPct(a08.sequential_sessions), accent: "green", hint: "One-after-another sessions" },
        { label: "Total", value: total, accent: "purple" },
      ]} />

      <div className="grid md:grid-cols-2 gap-3 mt-4">
        {srcData.length > 0 && (
          <ChartCard title="Source Distribution" description="Which AI CLI tools are used">
            <div className="space-y-2.5 py-1">
              {srcData.sort((a, b) => b.value - a.value).map((d, i) => {
                const srcTotal = srcData.reduce((s, x) => s + x.value, 0);
                const pct = srcTotal > 0 ? ((d.value / srcTotal) * 100).toFixed(0) : "0";
                return (
                  <div key={d.name}>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-[12px] font-medium text-slate-700 capitalize">{d.name}</span>
                      <span className="text-[11px] text-slate-400 tabular-nums">{d.value} sessions ({pct}%)</span>
                    </div>
                    <div className="w-full bg-slate-100 rounded h-2.5">
                      <div className="h-2.5 rounded transition-all" style={{ width: `${pct}%`, backgroundColor: COLORS[i % COLORS.length] }} />
                    </div>
                  </div>
                );
              })}
            </div>
          </ChartCard>
        )}

        <ChartCard title="Session Duration Distribution" description="How long sessions typically last">
          <ResponsiveContainer debounce={0} width="100%" height={280}>
            <BarChart data={durData} barSize={36} 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} domain={[0, (dataMax: number) => Math.ceil(dataMax * 1.2)]} />
              <Tooltip contentStyle={tooltipStyle} cursor={false} />
              <Bar isAnimationActive={false} dataKey="count" fill="#16a34a" radius={[4, 4, 0, 0]}>
                <LabelList dataKey="barLabel" position="top" fontSize={9} fill="#475569" fontWeight={500} />
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>
      </div>

      {mode === "dev" && scatterByDev.some((d) => d.data.length > 0) && (
        <div className="mt-3">
          <ChartCard title="Conversation Depth vs Duration" description="Each dot is a session">
            <ResponsiveContainer debounce={0} width="100%" height={320}>
              <ScatterChart margin={{ top: 16, bottom: 10 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                <XAxis dataKey="x" name="Duration (min)" tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false}
                  label={{ value: "Duration (min)", position: "bottom", fontSize: 10, fill: "#94a3b8", offset: -5 }} />
                <YAxis dataKey="y" name="Turns" tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false}
                  label={{ value: "Turns", angle: -90, position: "insideLeft", fontSize: 10, fill: "#94a3b8" }} />
                <Tooltip contentStyle={tooltipStyle} cursor={false} />
                <Legend verticalAlign="top" height={26} wrapperStyle={{ fontSize: 11 }} />
                {scatterByDev.map(({ dev, data: sd }) => (
                  <Scatter key={dev} name={dev} data={sd} fill={DEV_COLORS[dev] ?? "#94a3b8"} fillOpacity={0.5} r={4} />
                ))}
              </ScatterChart>
            </ResponsiveContainer>
          </ChartCard>
        </div>
      )}
    </Section>
  );
}
