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

interface DevActive {
  email: string;
  active_hours: number;
  wall_hours: number;
  idle_hours: number;
  active_pct: number;
  median_active_min: number;
  sessions_with_idle: number;
}

interface ChartData {
  active_time?: {
    headline: string;
    total_active_hours: number;
    total_wall_hours: number;
    total_idle_hours: number;
    active_pct: number;
    sessions_with_idle_gaps: number;
    caveat: string;
    by_developer: DevActive[];
    histogram: { range: string; count: number }[];
  };
}

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

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

  if (loading || !data.active_time?.by_developer) return null;

  const at = data.active_time;

  const devData = at.by_developer.map(d => ({
    name: shortEmail(d.email),
    active: d.active_hours,
    idle: Math.max(0, d.wall_hours - d.active_hours),
    active_pct: d.active_pct,
  }));

  const histData = at.histogram || [];

  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">
          Only <span className="text-accent">{at.active_pct.toFixed(0)}%</span> of AI time is real work.
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          {at.headline}. The rest is idle gaps where developers walked away or switched context.
          {at.sessions_with_idle_gaps > 0 && ` ${at.sessions_with_idle_gaps} sessions had gaps longer than 30 minutes.`}
        </p>
      </motion.div>

      {/* Big stat */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-6">
        <motion.div initial={{ opacity: 0, y: 10 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }}
          className="bg-accent/10 border border-accent/20 rounded-xl p-5 text-center">
          <div className="text-3xl font-bold text-accent">{at.total_active_hours.toFixed(0)}h</div>
          <div className="text-xs text-text-3 mt-1">active time</div>
        </motion.div>
        <motion.div initial={{ opacity: 0, y: 10 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ delay: 0.08 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5 text-center">
          <div className="text-3xl font-bold text-text-2">{at.total_wall_hours.toFixed(0)}h</div>
          <div className="text-xs text-text-3 mt-1">wall clock</div>
        </motion.div>
        <motion.div initial={{ opacity: 0, y: 10 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ delay: 0.16 }}
          className="bg-rose/5 border border-rose/20 rounded-xl p-5 text-center">
          <div className="text-3xl font-bold text-rose">{at.total_idle_hours.toFixed(0)}h</div>
          <div className="text-xs text-text-3 mt-1">idle time</div>
        </motion.div>
        <motion.div initial={{ opacity: 0, y: 10 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ delay: 0.24 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5 text-center">
          <div className="text-3xl font-bold text-text-1">{at.active_pct.toFixed(1)}%</div>
          <div className="text-xs text-text-3 mt-1">active rate</div>
        </motion.div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Per-developer stacked bar */}
        <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">Active vs Idle Hours (per Developer)</h3>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={devData} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis type="number" tick={{ fill: '#888', fontSize: 11 }} tickFormatter={v => `${v}h`} />
              <YAxis type="category" dataKey="name" width={120} tick={{ fill: '#ccc', fontSize: 11 }} />
              <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, name: any) => [`${Number(v ?? 0).toFixed(1)}h`, name]) as any}
              />
              <Bar dataKey="active" name="Active" stackId="a" fill="#6366f1" radius={[0, 0, 0, 0]} />
              <Bar dataKey="idle" name="Idle" stackId="a" fill="rgba(255,255,255,0.08)" radius={[0, 4, 4, 0]} />
            </BarChart>
          </ResponsiveContainer>
          {/* Active % labels */}
          <div className="flex flex-wrap gap-3 mt-3">
            {at.by_developer.map(d => (
              <span key={d.email} className="text-[10px] text-text-3">
                {shortEmail(d.email)}: <span className={d.active_pct < 50 ? 'text-rose font-semibold' : 'text-accent font-semibold'}>{d.active_pct.toFixed(0)}%</span> active
              </span>
            ))}
          </div>
        </motion.div>

        {/* Active time histogram */}
        {histData.length > 0 && (
          <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">Active Session Duration Distribution</h3>
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={histData}>
                <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                <XAxis dataKey="range" tick={{ fill: '#888', fontSize: 10 }} />
                <YAxis tick={{ fill: '#888', fontSize: 11 }} />
                <Tooltip
                  contentStyle={{ background: '#1a1a2e', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, fontSize: 12 }}
                />
                <Bar dataKey="count" name="Sessions" radius={[4, 4, 0, 0]}>
                  {histData.map((_, i) => (
                    <Cell key={i} fill={i < 2 ? 'rgba(255,255,255,0.12)' : '#6366f1'} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </motion.div>
        )}
      </div>

      {at.caveat && (
        <motion.div
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true }}
          transition={{ delay: 0.4 }}
          className="mt-4 bg-surface-2 border border-border-dim rounded-xl px-5 py-3 text-xs text-text-3"
        >
          {at.caveat}
        </motion.div>
      )}
    </section>
  );
}
