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", "#0891b2", "#dc2626", "#2563eb"];
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 ToolProfileSection({ data, derived }: Props) {
  const { mode } = useViewMode();
  const tt = derived.toolTotals;

  const barData = [
    { name: "Explore", count: tt.explore },
    { name: "Edit", count: tt.edit },
    { name: "Shell", count: tt.shell },
    { name: "Plan", count: tt.plan },
    { name: "Delegation", count: tt.delegation },
    { name: "Web", count: tt.web },
    { name: "MCP", count: tt.mcp },
  ].filter((d) => d.count > 0);
  const toolTotal = barData.reduce((s, d) => s + d.count, 0);
  const barDataLabeled = barData.map(d => ({ ...d, barLabel: `${d.count} (${toolTotal > 0 ? ((d.count / toolTotal) * 100).toFixed(0) : 0}%)` }));

  const dominantData = derived.dominantToolDistribution
    .filter((d) => d.value > 0)
    .sort((a, b) => b.value - a.value);
  const dominantTotal = dominantData.reduce((s, d) => s + d.value, 0);

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const sessions = data.a09_tool_profile.per_session as any[];
  const devNames = [...new Set(sessions.map((s: { developer?: string }) => s.developer).filter(Boolean))] as string[];
  const devToolData = devNames.map((dev) => {
    const ds = sessions.filter((s: { developer?: string }) => s.developer === dev);
    return {
      name: dev,
      explore: ds.reduce((sum: number, s: { explore_count: number }) => sum + s.explore_count, 0),
      edit: ds.reduce((sum: number, s: { edit_count: number }) => sum + s.edit_count, 0),
      shell: ds.reduce((sum: number, s: { shell_count: number }) => sum + s.shell_count, 0),
    };
  });

  return (
    <Section id="tool-profile" title="Tool Profile" subtitle="How AI tools are used across sessions">
      <MetricStrip metrics={[
        { label: "Total Tool Calls", value: (tt.explore + tt.edit + tt.shell + tt.plan + tt.delegation + tt.web + tt.mcp).toLocaleString(), accent: "blue", hint: "Sum of all AI tool invocations" },
        { label: "Explore/Edit Ratio", value: derived.exploreEditRatio.toFixed(1) + "x", accent: "purple", hint: "How much reading vs writing AI does" },
        { label: "Unique Categories", value: barData.length, accent: "green", hint: "Different types of tools used" },
        { label: "Dominant", value: derived.dominantToolDistribution[0]?.name ?? "\u2014", accent: "amber", hint: "Most frequently used tool category" },
      ]} />

      <div className="grid md:grid-cols-2 gap-3 mt-4">
        <ChartCard title="Tool Category Totals" description="Total invocations across all sessions">
          <ResponsiveContainer debounce={0} width="100%" height={barData.length * 44 + 20}>
            <BarChart data={barDataLabeled} layout="vertical" barSize={22} margin={{ right: 50 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" horizontal={false} />
              <XAxis type="number" tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false} />
              <YAxis type="category" dataKey="name" tick={{ fontSize: 11, fill: "#334155", fontWeight: 500 }} axisLine={false} tickLine={false} width={80} />
              <Tooltip contentStyle={tooltipStyle} cursor={false} />
              <Bar isAnimationActive={false} dataKey="count" radius={[0, 4, 4, 0]}>
                <LabelList dataKey="barLabel" position="right" fontSize={10} fill="#64748b" fontWeight={500} />
                {barData.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>

        <ChartCard title="Dominant Tool per Session" description="Which tool category was used most in each session">
          <div className="space-y-2.5 py-1">
            {dominantData.map((d, i) => {
              const pct = dominantTotal > 0 ? ((d.value / dominantTotal) * 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">{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>
      </div>

      {mode === "dev" && devToolData.length > 0 && (
        <div className="mt-3">
          <ChartCard title="Tool Usage by Developer" description="Explore / Edit / Shell breakdown">
            <ResponsiveContainer debounce={0} width="100%" height={280}>
              <BarChart data={devToolData} barSize={20} 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} />
                <Tooltip contentStyle={tooltipStyle} cursor={false} />
                <Legend verticalAlign="top" height={26} wrapperStyle={{ fontSize: 11 }} />
                <Bar isAnimationActive={false} dataKey="explore" name="Explore" fill="#4f46e5" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="explore" position="top" fontSize={9} fill="#64748b" />
                </Bar>
                <Bar isAnimationActive={false} dataKey="edit" name="Edit" fill="#16a34a" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="edit" position="top" fontSize={9} fill="#64748b" />
                </Bar>
                <Bar isAnimationActive={false} dataKey="shell" name="Shell" fill="#d97706" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="shell" position="top" fontSize={9} fill="#64748b" />
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ChartCard>
        </div>
      )}
    </Section>
  );
}
