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 COLORS = ["#dc2626", "#2563eb", "#d97706", "#7c3aed", "#0891b2", "#16a34a"];
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" };

export function PromptQualitySection({ data }: { data: AllData }) {
  const { mode } = useViewMode();
  const a03 = data.a03_prompt_signals;
  const a06 = data.a06_ai_clarification;
  const p = data.c01_developer_profile.profile;
  const total = a03.total_sessions;
  const fmtPct = (n: number, d: number) => d > 0 ? `${((n / d) * 100).toFixed(1)}%` : "0%";

  // Compute median first prompt length from per-session data
  const promptLens = a03.per_session
    .map((s) => s.first_prompt_char_len)
    .filter((len) => len > 0)
    .sort((a, b) => a - b);
  const medianPromptLen = promptLens.length > 0
    ? promptLens.length % 2 === 1
      ? promptLens[Math.floor(promptLens.length / 2)]
      : Math.round((promptLens[promptLens.length / 2 - 1] + promptLens[promptLens.length / 2]) / 2)
    : 0;

  const signalData = [
    { name: "Error Paste", count: a03.sessions_with_error_paste },
    { name: "URL", count: a03.sessions_with_url },
    { name: "Terse", count: a03.sessions_with_terse },
    { name: "Code Paste", count: a03.per_session.filter((s) => s.has_code_paste).length },
    { name: "Terminal", count: a03.per_session.filter((s) => s.has_terminal_output).length },
    { name: "Structured", count: a03.per_session.filter((s) => s.has_structured_data).length },
  ].map(d => ({
    ...d,
    pct: total > 0 ? +((d.count / total) * 100).toFixed(1) : 0,
    barLabel: `${d.count} (${total > 0 ? ((d.count / total) * 100).toFixed(0) : 0}%)`,
  }));

  const lenBuckets: Record<string, number> = {};
  const bucketSize = 200;
  for (const s of a03.per_session) {
    if (s.first_prompt_char_len > 0) {
      const b = Math.floor(s.first_prompt_char_len / bucketSize) * bucketSize;
      const key = b >= 1000 ? "1000+" : `${b}-${b + bucketSize}`;
      lenBuckets[key] = (lenBuckets[key] || 0) + 1;
    }
  }
  const lenTotal = Object.values(lenBuckets).reduce((a, b) => a + b, 0);
  const lenData = Object.entries(lenBuckets)
    .map(([name, count]) => ({ name, count, barLabel: `${count} (${lenTotal > 0 ? ((count / lenTotal) * 100).toFixed(0) : 0}%)` }))
    .sort((a, b) => parseInt(a.name) - parseInt(b.name));

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const sessions = a03.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;
    const avgLen = dt > 0 ? Math.round(ds.reduce((sum: number, s: { first_prompt_char_len: number }) => sum + s.first_prompt_char_len, 0) / dt) : 0;
    const tersePct = dt > 0 ? +((ds.filter((s: { prompt_is_terse: boolean }) => s.prompt_is_terse).length / dt) * 100).toFixed(1) : 0;
    return { name: dev, avgPromptLen: avgLen, tersePct, lenLabel: `${avgLen}`, terseLabel: `${tersePct}%` };
  });

  return (
    <Section id="prompt-quality" title="Prompt Quality" subtitle="How developers communicate with AI">
      <MetricStrip metrics={[
        { label: "Clarification Rate", value: fmtPct(a06.sessions_with_clarification, a06.total_sessions), accent: "purple", hint: "Sessions where AI asked for more info" },
        { label: "Median 1st Prompt", value: `${medianPromptLen}`, sub: `chars (avg ${Math.round(p.avg_first_prompt_length)})`, accent: "blue", hint: "Median length of initial prompt — average is skewed by long error pastes and code dumps" },
        { label: "Terse Prompts", value: a03.sessions_with_terse, sub: `of ${total} (${fmtPct(a03.sessions_with_terse, total)})`, accent: "amber", hint: "Very short prompts (<50 chars)" },
        { label: "Error Pastes", value: a03.sessions_with_error_paste, sub: `of ${total} (${fmtPct(a03.sessions_with_error_paste, total)})`, accent: "red", hint: "Sessions started by pasting an error" },
      ]} />

      <div className={`grid ${mode === "dev" ? "md:grid-cols-2" : ""} gap-3 mt-4`}>
        <ChartCard title="Prompt Signal Frequencies" description="Context types included in prompts">
          <ResponsiveContainer debounce={0} width="100%" height={280}>
            <BarChart data={signalData} barSize={32} 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} 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="barLabel" position="top" fontSize={9} fill="#475569" fontWeight={500} />
                {signalData.map((_, i) => <Cell key={i} fill={COLORS[i]} />)}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>

        {mode === "dev" && lenData.length > 0 && (
          <ChartCard title="First Prompt Length Distribution" description="Opening prompt character count">
            <ResponsiveContainer debounce={0} width="100%" height={280}>
              <BarChart data={lenData} barSize={28} margin={{ top: 28 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" vertical={false} />
                <XAxis dataKey="name" tick={{ fontSize: 9, fill: "#64748b", 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="#0891b2" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="barLabel" position="top" fontSize={9} fill="#475569" fontWeight={500} />
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ChartCard>
        )}
      </div>

      {mode === "dev" && devCompare.length > 0 && (
        <div className="grid md:grid-cols-2 gap-3 mt-3">
          <ChartCard title="Avg Prompt Length by Developer">
            <ResponsiveContainer debounce={0} width="100%" height={220}>
              <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} domain={[0, (dataMax: number) => Math.ceil(dataMax * 1.2)]} />
                <Tooltip contentStyle={tooltipStyle} cursor={false} formatter={(value) => [`${Number(value ?? 0)} chars`, ""]} />
                <Bar isAnimationActive={false} dataKey="avgPromptLen" name="Avg Chars" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="lenLabel" position="top" fontSize={10} fill="#475569" fontWeight={500} />
                  {devCompare.map((_, i) => <Cell key={i} fill={DEV_COLORS[i]} />)}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ChartCard>
          <ChartCard title="Terse Prompt Rate by Developer">
            <ResponsiveContainer debounce={0} width="100%" height={220}>
              <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="%" />
                <Tooltip contentStyle={tooltipStyle} cursor={false} />
                <Bar isAnimationActive={false} dataKey="tersePct" name="Terse %" radius={[4, 4, 0, 0]}>
                  <LabelList dataKey="terseLabel" position="top" fontSize={10} fill="#475569" fontWeight={500} />
                  {devCompare.map((_, i) => <Cell key={i} fill={DEV_COLORS[i]} />)}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </ChartCard>
        </div>
      )}
    </Section>
  );
}
