import { useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { useTimezone } from '../hooks/useTimezone';

interface TimelineSession {
  session_id: string;
  user: string;
  source: string;
  repo: string | null;
  start: string;
  end: string;
  duration_min: number;
}

const SOURCE_COLORS: Record<string, string> = {
  claude_code: '#818cf8',
  codex_cli: '#34d399',
  gemini_cli: '#22d3ee',
  cursor: '#fbbf24',
};

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

export default function SessionTimeline() {
  const { data, loading } = useData<{ sessions: TimelineSession[] }>('/data/sessions_timeline.json', { sessions: [] });
  const [selectedDay, setSelectedDay] = useState<string | null>(null);
  const { tz, formatTime, formatDate: fmtDate, tzLabel } = useTimezone();

  const { days, dayMap } = useMemo(() => {
    if (!data.sessions.length) return { days: [], dayMap: new Map<string, TimelineSession[]>() };

    const map = new Map<string, TimelineSession[]>();
    for (const s of data.sessions) {
      if (s.duration_min < 1) continue; // skip single-interaction
      const day = s.start.slice(0, 10);
      if (!map.has(day)) map.set(day, []);
      map.get(day)!.push(s);
    }
    const sorted = [...map.keys()].sort();
    return { days: sorted, dayMap: map };
  }, [data.sessions]);

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

  const active = selectedDay || days[days.length - 1];
  const sessions = dayMap.get(active) || [];

  // Find time range for the day
  const starts = sessions.map(s => new Date(s.start).getTime());
  const ends = sessions.map(s => new Date(s.end).getTime());
  const dayStart = Math.min(...starts);
  const dayEnd = Math.max(...ends);
  const dayRange = dayEnd - dayStart || 1;

  // Group by user
  const userSessions = new Map<string, TimelineSession[]>();
  for (const s of sessions) {
    const u = shortEmail(s.user);
    if (!userSessions.has(u)) userSessions.set(u, []);
    userSessions.get(u)!.push(s);
  }
  const users = [...userSessions.keys()].sort();

  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">
          When your team actually codes with AI.
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          Each bar is a session. Width = duration. Color = CLI tool.
          Notice how sessions cluster — developers work in bursts, not steady streams.
        </p>
      </motion.div>

      {/* Day selector */}
      <div className="flex gap-2 mb-6 flex-wrap">
        {days.map(day => {
          const count = dayMap.get(day)?.length || 0;
          const isActive = day === active;
          return (
            <button
              key={day}
              onClick={() => setSelectedDay(day)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                isActive
                  ? 'bg-accent text-white'
                  : 'bg-surface-2 text-text-3 hover:text-text-2 border border-border-dim'
              }`}
            >
              {fmtDate(day + 'T12:00:00Z')}
              <span className="ml-1.5 opacity-70">({count})</span>
            </button>
          );
        })}
      </div>

      {/* Timeline */}
      <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 overflow-x-auto"
      >
        {/* Time axis */}
        <div className="flex justify-between text-[10px] text-text-3 mb-3 pl-24">
          {[0, 0.25, 0.5, 0.75, 1].map(frac => {
            const t = new Date(dayStart + frac * dayRange);
            return (
              <span key={frac}>
                {formatTime(t.toISOString())} {tzLabel}
              </span>
            );
          })}
        </div>

        {/* Rows per user */}
        <div className="space-y-2">
          {users.map(user => {
            const uSessions = userSessions.get(user) || [];
            return (
              <div key={user} className="flex items-center gap-3">
                <div className="w-20 text-xs font-medium text-text-2 truncate shrink-0 text-right">
                  {user}
                </div>
                <div className="flex-1 relative h-7 bg-surface-2 rounded-md">
                  {uSessions.map(s => {
                    const sStart = new Date(s.start).getTime();
                    const sEnd = new Date(s.end).getTime();
                    const left = ((sStart - dayStart) / dayRange) * 100;
                    const width = Math.max(((sEnd - sStart) / dayRange) * 100, 0.5);
                    return (
                      <div
                        key={s.session_id}
                        className="absolute top-1 bottom-1 rounded-sm opacity-80 hover:opacity-100 transition-opacity cursor-default group"
                        style={{
                          left: `${left}%`,
                          width: `${width}%`,
                          background: SOURCE_COLORS[s.source] || '#63637a',
                          minWidth: '3px',
                        }}
                        title={`${s.source.replace('_', ' ')} — ${s.duration_min.toFixed(0)}min${s.repo ? ` — ${s.repo.split('/').pop()}` : ''}`}
                      />
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>

        {/* Legend */}
        <div className="flex flex-wrap gap-3 justify-center mt-4 pt-3 border-t border-border-dim">
          {Object.entries(SOURCE_COLORS).map(([k, c]) => (
            <div key={k} className="flex items-center gap-1.5 text-xs text-text-3">
              <div className="w-2.5 h-2.5 rounded-sm" style={{ background: c }} />
              {k.replace('_', ' ')}
            </div>
          ))}
        </div>
      </motion.div>

      <div className="mt-4 text-xs text-text-3 text-center">
        Showing {sessions.length} sessions with duration &gt; 1 minute
      </div>
    </section>
  );
}
