import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, Cell, Legend, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, LabelList } from "recharts";
import { ChartCard } from "../../components/ChartCard";
import { Section } from "../../components/Section";
import { useViewMode } from "../../context/ViewModeContext";
import type { AllData, WeekData } from "../../types/data";

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 WeeklyTrendsSection({ data }: { data: AllData }) {
  const { mode } = useViewMode();
  const weeks = data.c02_team_trends.weeks;

  const devWeeks = weeks.filter((w) => (w as WeekData & { developer?: string }).developer) as (WeekData & { developer: string })[];
  const devNames = [...new Set(devWeeks.map((w) => w.developer))];

  if (devWeeks.length === 0) {
    return (
      <Section id="weekly-trends" title="Developer Comparison" subtitle="Cross-developer analytics">
        <div className="bg-white rounded-lg p-10 border border-slate-200 text-center">
          <p className="text-sm text-slate-400">Insufficient data for comparison.</p>
        </div>
      </Section>
    );
  }

  const totalCost = devWeeks.reduce((s, w) => s + w.total_cost, 0);

  const compareData = devWeeks.map((w) => ({
    name: w.developer,
    sessions: w.sessions_count,
    sessionsLabel: `${w.sessions_count}`,
    cost: +w.total_cost.toFixed(2),
    costLabel: `$${w.total_cost.toFixed(0)}`,
    costPct: totalCost > 0 ? +((w.total_cost / totalCost) * 100).toFixed(1) : 0,
    costPerSession: +w.avg_session_cost.toFixed(2),
    costPerLabel: `$${w.avg_session_cost.toFixed(2)}`,
    editPct: +(w.edit_sessions_pct * 100).toFixed(1),
    interruptRate: +(w.interrupt_rate * 100).toFixed(1),
  }));

  const maxSessions = Math.max(...compareData.map((d) => d.sessions), 1);
  const maxCost = Math.max(...compareData.map((d) => d.cost), 1);
  const radarData = [
    { metric: "Sessions", ...Object.fromEntries(compareData.map((d) => [d.name, +((d.sessions / maxSessions) * 100).toFixed(0)])) },
    { metric: "Edit Rate", ...Object.fromEntries(compareData.map((d) => [d.name, d.editPct])) },
    { metric: "Int. Rate", ...Object.fromEntries(compareData.map((d) => [d.name, d.interruptRate])) },
    { metric: "Cost %", ...Object.fromEntries(compareData.map((d) => [d.name, +((d.cost / maxCost) * 100).toFixed(0)])) },
  ];

  const srcByDev = devWeeks.map((w) => ({
    name: w.developer,
    ...Object.fromEntries(Object.entries(w.source_distribution).map(([k, v]) => [k.replace(/_/g, " "), v])),
  }));
  const allSources = [...new Set(devWeeks.flatMap((w) => Object.keys(w.source_distribution)))];
  const srcColors: Record<string, string> = { claude_code: "#2563eb", cursor: "#16a34a", gemini_cli: "#d97706", codex_cli: "#7c3aed" };

  return (
    <Section id="weekly-trends" title="Developer Comparison" subtitle="Cross-developer metrics and patterns">
      <div className="grid md:grid-cols-2 gap-3">
        <ChartCard title="Sessions by Developer">
          <ResponsiveContainer debounce={0} width="100%" height={260}>
            <BarChart data={compareData} 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} domain={[0, (dataMax: number) => Math.ceil(dataMax * 1.2)]} />
              <Tooltip contentStyle={tooltipStyle} cursor={false} />
              <Bar isAnimationActive={false} dataKey="sessions" radius={[4, 4, 0, 0]}>
                <LabelList dataKey="sessionsLabel" position="top" fontSize={10} fill="#475569" fontWeight={500} />
                {compareData.map((d) => <Cell key={d.name} fill={DEV_COLORS[d.name] ?? "#94a3b8"} />)}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>

        <ChartCard title="Total Cost by Developer">
          <ResponsiveContainer debounce={0} width="100%" height={260}>
            <BarChart data={compareData} 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} domain={[0, (dataMax: number) => Math.ceil(dataMax * 1.2)]} />
              <Tooltip contentStyle={tooltipStyle} cursor={false} formatter={(value) => [`$${Number(value ?? 0).toFixed(2)}`, ""]} />
              <Bar isAnimationActive={false} dataKey="cost" radius={[4, 4, 0, 0]}>
                <LabelList dataKey="costLabel" position="top" fontSize={10} fill="#475569" fontWeight={500} />
                {compareData.map((d) => <Cell key={d.name} fill={DEV_COLORS[d.name] ?? "#94a3b8"} />)}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>

        <ChartCard title="Developer Profile Radar" description="Normalized comparison across key metrics">
          <ResponsiveContainer debounce={0} width="100%" height={300}>
            <RadarChart data={radarData} cx="50%" cy="50%" outerRadius="70%">
              <PolarGrid stroke="#e2e8f0" />
              <PolarAngleAxis dataKey="metric" tick={{ fontSize: 10, fill: "#64748b", fontWeight: 500 }} />
              <PolarRadiusAxis tick={{ fontSize: 9, fill: "#94a3b8" }} />
              {devNames.map((dev) => (
                <Radar key={dev} name={dev} dataKey={dev} stroke={DEV_COLORS[dev] ?? "#94a3b8"} fill={DEV_COLORS[dev] ?? "#94a3b8"} fillOpacity={0.1} strokeWidth={1.5} />
              ))}
              <Tooltip contentStyle={tooltipStyle} cursor={false} />
              <Legend verticalAlign="top" height={26} wrapperStyle={{ fontSize: 11 }} />
            </RadarChart>
          </ResponsiveContainer>
        </ChartCard>

        <ChartCard title="Source Usage by Developer" description="Tool preferences per developer">
          <ResponsiveContainer debounce={0} width="100%" height={300}>
            <BarChart data={srcByDev} barSize={28} margin={{ top: 20 }}>
              <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 }} />
              {allSources.map((src) => (
                <Bar isAnimationActive={false} key={src} dataKey={src.replace(/_/g, " ")} stackId="a" fill={srcColors[src] ?? "#94a3b8"} radius={[0, 0, 0, 0]} />
              ))}
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>
      </div>

      {mode === "dev" && (
        <div className="grid md:grid-cols-2 gap-3 mt-3">
          <ChartCard title="Cost per Session by Developer">
            <ResponsiveContainer debounce={0} width="100%" height={240}>
              <BarChart data={compareData} 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} domain={[0, (dataMax: number) => Math.ceil(dataMax * 1.2)]} />
                <Tooltip contentStyle={tooltipStyle} cursor={false} formatter={(v) => [`$${Number(v ?? 0).toFixed(2)}`, ""]} />
                <Bar isAnimationActive={false} dataKey="costPerSession" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="costPerLabel" position="top" fontSize={10} fill="#475569" fontWeight={500} />
                  {compareData.map((d) => <Cell key={d.name} fill={DEV_COLORS[d.name] ?? "#94a3b8"} />)}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ChartCard>

          <ChartCard title="Edit Rate vs Interrupt Rate" description="Higher edit + lower interrupt = better">
            <ResponsiveContainer debounce={0} width="100%" height={240}>
              <BarChart data={compareData} barSize={24} 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="#16a34a" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="editPct" position="top" fontSize={9} fill="#64748b" formatter={(v) => `${v}%`} />
                </Bar>
                <Bar isAnimationActive={false} dataKey="interruptRate" name="Interrupt %" fill="#dc2626" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="interruptRate" position="top" fontSize={9} fill="#64748b" formatter={(v) => `${v}%`} />
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ChartCard>
        </div>
      )}
    </Section>
  );
}
