import { useMemo } from 'react';
import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts';

interface WorkflowData {
  top_trigrams: Array<{ pattern: string; count: number }>;
  headline: string;
}

interface ResponseData {
  median_seconds: number;
  mean_seconds: number;
  p95_seconds: number;
  histogram: { counts: number[]; edges: number[] };
  headline: string;
}

interface EfficiencyData {
  counts: number[];
  edges: number[];
  labels: string[];
  mean: number;
  median: number;
}

interface ChartData {
  workflow_patterns: WorkflowData;
  response_time: ResponseData;
  efficiency_distribution: EfficiencyData;
}

const FLOW_COLORS: Record<string, string> = {
  shell: '#22d3ee',
  explore: '#818cf8',
  edit: '#34d399',
  planning: '#fbbf24',
};

function patternColor(pattern: string): string {
  const parts = pattern.split(' → ');
  // Use color of the dominant action
  const counts: Record<string, number> = {};
  parts.forEach(p => { counts[p] = (counts[p] || 0) + 1; });
  const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0];
  return FLOW_COLORS[dominant || ''] || '#63637a';
}

const CustomTooltip = ({ active, payload }: any) => {
  if (!active || !payload?.length) return null;
  const d = payload[0]?.payload;
  return (
    <div className="bg-surface-3 border border-border-dim rounded-lg px-3 py-2 text-xs shadow-xl">
      <div className="text-text-2 mb-1 font-mono">{d?.pattern || d?.range}</div>
      <div className="text-text-1 font-semibold">{d?.count?.toLocaleString() || payload[0]?.value?.toLocaleString()} occurrences</div>
    </div>
  );
};

export default function WorkflowPatterns() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {
    workflow_patterns: { top_trigrams: [], headline: '' },
    response_time: { median_seconds: 0, mean_seconds: 0, p95_seconds: 0, histogram: { counts: [], edges: [] }, headline: '' },
    efficiency_distribution: { counts: [], edges: [], labels: [], mean: 0, median: 0 },
  });

  const { trigramData, responseHistData, efficiencyData } = useMemo(() => {
    const trigrams = data.workflow_patterns?.top_trigrams || [];
    const trigramData = trigrams.slice(0, 10).map(t => ({
      pattern: t.pattern,
      count: t.count,
      fill: patternColor(t.pattern),
    }));

    const rh = data.response_time?.histogram;
    const responseHistData = rh?.counts?.map((count: number, i: number) => ({
      range: `${rh.edges[i].toFixed(0)}s`,
      count,
    })) || [];

    const eff = data.efficiency_distribution;
    const efficiencyData = eff?.counts?.map((count: number, i: number) => ({
      range: eff.labels?.[i] || `${eff.edges[i]}-${eff.edges[i + 1]}`,
      count,
    })) || [];

    return { trigramData, responseHistData, efficiencyData };
  }, [data]);

  if (loading || !trigramData.length) return null;

  const rt = data.response_time;
  const eff = data.efficiency_distribution;

  return (
    <section className="px-8 max-w-7xl mx-auto py-20">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true }}
        transition={{ duration: 0.6 }}
      >
        <h2 className="text-3xl md:text-4xl font-bold mb-2">
          {data.workflow_patterns?.top_trigrams?.[0]
            ? <>{data.workflow_patterns.top_trigrams[0].pattern}. <span className="text-cyan">{data.workflow_patterns.top_trigrams[0].count.toLocaleString()} times.</span></>
            : <>Workflow Patterns</>
          }
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          {data.workflow_patterns?.headline || 'The most common 3-step workflows reveal how your AI agents actually operate.'}
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Workflow trigrams */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.1, duration: 0.5 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5 lg:col-span-1"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
            Top Workflow Patterns (3-step)
          </h3>
          <ResponsiveContainer width="100%" height={340}>
            <BarChart data={trigramData} layout="vertical" margin={{ left: 0, right: 20 }}>
              <XAxis type="number" hide />
              <YAxis type="category" dataKey="pattern" width={150} tick={{ fontSize: 10, fontFamily: 'monospace' }} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="count" radius={[0, 4, 4, 0]}>
                {trigramData.map((d, i) => (
                  <Cell key={i} fill={d.fill} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </motion.div>

        {/* Response time histogram */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2, duration: 0.5 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
            AI Response Time
          </h3>
          <ResponsiveContainer width="100%" height={240}>
            <BarChart data={responseHistData.slice(0, 12)} margin={{ bottom: 20 }}>
              <XAxis dataKey="range" tick={{ fontSize: 9 }} interval={1} />
              <YAxis tick={{ fontSize: 10 }} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="count" fill="#22d3ee" radius={[3, 3, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
          <div className="grid grid-cols-3 gap-2 mt-3">
            <div className="bg-surface-2 rounded-lg p-2.5 text-center">
              <div className="text-lg font-bold text-cyan">{rt.median_seconds}s</div>
              <div className="text-[10px] text-text-3">Median</div>
            </div>
            <div className="bg-surface-2 rounded-lg p-2.5 text-center">
              <div className="text-lg font-bold text-text-1">{rt.mean_seconds}s</div>
              <div className="text-[10px] text-text-3">Mean</div>
            </div>
            <div className="bg-surface-2 rounded-lg p-2.5 text-center">
              <div className="text-lg font-bold text-amber">{rt.p95_seconds}s</div>
              <div className="text-[10px] text-text-3">p95</div>
            </div>
          </div>
        </motion.div>

        {/* Efficiency distribution */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.3, duration: 0.5 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
            Session Efficiency Score
          </h3>
          <ResponsiveContainer width="100%" height={240}>
            <BarChart data={efficiencyData} margin={{ bottom: 20 }}>
              <XAxis
                dataKey="range"
                tick={{ fontSize: 9 }}
                label={{ value: 'Score %', position: 'insideBottom', offset: -10, fontSize: 10, fill: '#63637a' }}
              />
              <YAxis tick={{ fontSize: 10 }} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="count" fill="#a78bfa" radius={[3, 3, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
          <div className="grid grid-cols-2 gap-2 mt-3">
            <div className="bg-surface-2 rounded-lg p-2.5 text-center">
              <div className="text-lg font-bold text-purple">{eff.median}%</div>
              <div className="text-[10px] text-text-3">Median Score</div>
            </div>
            <div className="bg-surface-2 rounded-lg p-2.5 text-center">
              <div className="text-lg font-bold text-text-1">{eff.mean}%</div>
              <div className="text-[10px] text-text-3">Mean Score</div>
            </div>
          </div>
          {(() => {
            const lowCount = eff.counts?.[0] || 0;
            const totalSessions = eff.counts?.reduce((a: number, b: number) => a + b, 0) || 1;
            const lowPct = Math.round((lowCount / totalSessions) * 100);
            const aboveFifty = (eff.counts || []).slice(5).reduce((a: number, b: number) => a + b, 0);
            return (
              <div className="mt-3 space-y-2">
                <div className="text-[10px] text-text-3">
                  Efficiency = ratio of edit actions to total actions.
                </div>
                <div className="bg-rose/5 border border-rose/20 rounded-lg p-2.5 text-[11px] text-text-2">
                  <span className="font-semibold text-rose">{lowPct}% of sessions score below 10</span> — no edits, high discovery overhead.
                  Only {aboveFifty} of {totalSessions} sessions ({Math.round((aboveFifty / totalSessions) * 100)}%) score above 50.
                </div>
              </div>
            );
          })()}
        </motion.div>
      </div>
    </section>
  );
}

