import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';

interface DailyPoint {
  date: string;
  sessions: number;
  edits: number;
  cost: number;
  edits_per_session: number;
  cost_per_session: number;
  explore_to_edit: number;
}

interface DevCurve {
  daily: DailyPoint[];
  trend: string;
  total_sessions: number;
  total_cost: number;
}

interface ChartData {
  learning_curves?: {
    headline: string;
    developers: Record<string, DevCurve>;
  };
}

const DEV_COLORS = ['#6366f1', '#f43f5e', '#f59e0b', '#10b981', '#8b5cf6'];

function shortEmail(email: string): string {
  const at = email.indexOf('@');
  return at > 0 ? email.slice(0, at) : email;
}

export default function LearningCurves() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {});

  if (loading || !data.learning_curves?.developers) return null;

  const { headline, developers } = data.learning_curves;
  const devEntries = Object.entries(developers).filter(([, v]) => Array.isArray(v?.daily) && v.daily.length > 0);

  if (devEntries.length === 0) return null;

  // Merge all daily data into a unified timeline
  const allDates = new Set<string>();
  devEntries.forEach(([, v]) => v.daily.forEach(d => allDates.add(d.date)));
  const dates = [...allDates].sort();

  const costData = dates.map(date => {
    const point: Record<string, number | string> = { date: date.slice(5) }; // MM-DD
    devEntries.forEach(([email, dev]) => {
      const match = dev.daily.find(d => d.date === date);
      point[shortEmail(email)] = match?.cost_per_session ?? 0;
    });
    return point;
  });

  const editsData = dates.map(date => {
    const point: Record<string, number | string> = { date: date.slice(5) };
    devEntries.forEach(([email, dev]) => {
      const match = dev.daily.find(d => d.date === date);
      point[shortEmail(email)] = match?.edits_per_session ?? 0;
    });
    return point;
  });

  const trendColors: Record<string, string> = {
    improving: '#10b981',
    stable: '#f59e0b',
    worsening: '#f43f5e',
  };

  const worseningCount = devEntries.filter(([, v]) => v.trend === 'worsening').length;

  return (
    <section className="px-8 max-w-7xl mx-auto py-16">
      <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">
          {worseningCount === devEntries.length
            ? <>Every developer is getting <span className="text-rose">more expensive</span> over time.</>
            : headline}
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          Daily cost and edit trends per developer. A downward cost curve means the developer is becoming more efficient with AI.
        </p>
      </motion.div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Cost per session trend */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.1 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5"
        >
          <h3 className="text-sm font-semibold text-text-2 mb-4">Cost per Session (USD/day)</h3>
          <ResponsiveContainer width="100%" height={220}>
            <LineChart data={costData}>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis dataKey="date" tick={{ fill: '#888', fontSize: 11 }} />
              <YAxis tick={{ fill: '#888', fontSize: 11 }} tickFormatter={v => `$${v}`} />
              <Tooltip
                contentStyle={{ background: '#1a1a2e', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, fontSize: 12 }}
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                formatter={((v: any) => [`$${Number(v ?? 0).toFixed(2)}`]) as any}
              />
              <Legend wrapperStyle={{ fontSize: 11 }} />
              {devEntries.map(([email], i) => (
                <Line
                  key={email}
                  type="monotone"
                  dataKey={shortEmail(email)}
                  stroke={DEV_COLORS[i % DEV_COLORS.length]}
                  strokeWidth={2}
                  dot={{ r: 3 }}
                  connectNulls
                />
              ))}
            </LineChart>
          </ResponsiveContainer>
        </motion.div>

        {/* Edits per session trend */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5"
        >
          <h3 className="text-sm font-semibold text-text-2 mb-4">Edits per Session (daily avg)</h3>
          <ResponsiveContainer width="100%" height={220}>
            <LineChart data={editsData}>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis dataKey="date" tick={{ fill: '#888', fontSize: 11 }} />
              <YAxis tick={{ fill: '#888', fontSize: 11 }} />
              <Tooltip
                contentStyle={{ background: '#1a1a2e', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, fontSize: 12 }}
              />
              <Legend wrapperStyle={{ fontSize: 11 }} />
              {devEntries.map(([email], i) => (
                <Line
                  key={email}
                  type="monotone"
                  dataKey={shortEmail(email)}
                  stroke={DEV_COLORS[i % DEV_COLORS.length]}
                  strokeWidth={2}
                  dot={{ r: 3 }}
                  connectNulls
                />
              ))}
            </LineChart>
          </ResponsiveContainer>
        </motion.div>
      </div>

      {/* Trend badges per developer */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mt-4">
        {devEntries.map(([email, dev], i) => (
          <motion.div
            key={email}
            initial={{ opacity: 0, y: 10 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ delay: 0.3 + i * 0.08 }}
            className="bg-surface-1 border border-border-dim rounded-xl p-4 flex items-center justify-between"
          >
            <div>
              <div className="text-sm font-semibold text-text-1 mb-0.5">{shortEmail(email)}</div>
              <div className="text-xs text-text-3">{dev.total_sessions} sessions, ${dev.total_cost.toFixed(0)} total</div>
            </div>
            <span
              className="text-[10px] font-semibold uppercase tracking-wider px-2.5 py-1 rounded-full"
              style={{
                color: trendColors[dev.trend] || '#888',
                background: `${trendColors[dev.trend] || '#888'}20`,
              }}
            >
              {dev.trend}
            </span>
          </motion.div>
        ))}
      </div>
    </section>
  );
}
