import { useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { ChevronUp, ChevronDown, Search, X } from 'lucide-react';

interface Session {
  session_id: string;
  source: string;
  user_email: string | number | null;
  repo_name: string | null;
  first_seen: string;
  duration_min: number;
  user: number;
  tool_call: number;
  explore: number;
  edit: number;
  shell: number;
  input_tokens: number;
  output_tokens: number;
  discovery_overhead: number | null;
  success_rate: number | null;
}

type SortKey = 'duration_min' | 'tool_call' | 'edit' | 'explore' | 'output_tokens' | 'first_seen';

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

function shortRepo(repo: string | null): string {
  if (!repo) return '—';
  const parts = repo.split('/');
  return parts[parts.length - 1] || repo;
}

function shortEmail(email: string | number | null): string {
  if (!email || typeof email !== 'string') return '—';
  const at = email.indexOf('@');
  return at > 0 ? email.slice(0, at) : email;
}

function fmtDuration(min: number): string {
  if (min < 1) return '<1m';
  if (min < 60) return `${Math.round(min)}m`;
  return `${Math.floor(min / 60)}h ${Math.round(min % 60)}m`;
}

function fmtTokens(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1000) return `${(n / 1000).toFixed(0)}k`;
  return String(n);
}

export default function SessionTable() {
  const { data, loading } = useData<{ sessions: Session[] }>('/data/session_metrics.json', { sessions: [] });
  const [sortKey, setSortKey] = useState<SortKey>('duration_min');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');
  const [filterText, setFilterText] = useState('');
  const sessions = useMemo(() => {
    let list = data.sessions
      .filter(s => {
        const email = typeof s.user_email === 'string' ? s.user_email : '';
        if (!filterText) return true;
        const q = filterText.toLowerCase();
        return email.toLowerCase().includes(q) ||
          (s.repo_name || '').toLowerCase().includes(q) ||
          s.source.toLowerCase().includes(q);
      });

    list.sort((a, b) => {
      const av = (a as any)[sortKey] ?? 0;
      const bv = (b as any)[sortKey] ?? 0;
      return sortDir === 'desc' ? bv - av : av - bv;
    });

    return list.slice(0, 50);
  }, [data.sessions, sortKey, sortDir, filterText]);

  if (loading || !data.sessions.length) return null;

  const toggleSort = (key: SortKey) => {
    if (sortKey === key) {
      setSortDir(d => d === 'desc' ? 'asc' : 'desc');
    } else {
      setSortKey(key);
      setSortDir('desc');
    }
  };

  const SortIcon = ({ k }: { k: SortKey }) => {
    if (sortKey !== k) return null;
    return sortDir === 'desc'
      ? <ChevronDown size={12} className="inline ml-0.5" />
      : <ChevronUp size={12} className="inline ml-0.5" />;
  };

  const thClass = 'px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-text-3 cursor-pointer hover:text-text-2 transition-colors select-none whitespace-nowrap';
  const tdClass = 'px-3 py-2.5 text-xs';

  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">
          Every session, dissected.
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          {data.sessions.length} sessions sorted by what matters. Search by developer, repo, or CLI.
        </p>
      </motion.div>

      {/* Filters */}
      <div className="flex items-center gap-3 mb-4">
        <div className="relative flex-1 max-w-xs">
          <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-3" />
          <input
            type="text"
            placeholder="Filter by dev, repo, CLI..."
            value={filterText}
            onChange={e => setFilterText(e.target.value)}
            className="w-full bg-surface-2 border border-border-dim rounded-lg pl-9 pr-8 py-2 text-xs text-text-1 placeholder-text-3 outline-none focus:border-accent transition-colors"
          />
          {filterText && (
            <button onClick={() => setFilterText('')} className="absolute right-2 top-1/2 -translate-y-1/2 text-text-3 hover:text-text-2">
              <X size={14} />
            </button>
          )}
        </div>
      </div>

      {/* Table */}
      <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 overflow-hidden"
      >
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-border-dim">
                <th className={thClass}>CLI</th>
                <th className={thClass}>Developer</th>
                <th className={thClass}>Repo</th>
                <th className={thClass} onClick={() => toggleSort('first_seen')}>
                  Date <SortIcon k="first_seen" />
                </th>
                <th className={thClass} onClick={() => toggleSort('duration_min')}>
                  Duration <SortIcon k="duration_min" />
                </th>
                <th className={thClass} onClick={() => toggleSort('tool_call')}>
                  Tools <SortIcon k="tool_call" />
                </th>
                <th className={thClass} onClick={() => toggleSort('explore')}>
                  Explore <SortIcon k="explore" />
                </th>
                <th className={thClass} onClick={() => toggleSort('edit')}>
                  Edits <SortIcon k="edit" />
                </th>
                <th className={thClass} onClick={() => toggleSort('output_tokens')}>
                  Output <SortIcon k="output_tokens" />
                </th>
              </tr>
            </thead>
            <tbody>
              {sessions.map((s, i) => (
                <tr
                  key={s.session_id}
                  className={`border-b border-border-dim/50 hover:bg-surface-2/40 transition-colors ${
                    i % 2 === 0 ? '' : 'bg-surface-0/30'
                  }`}
                >
                  <td className={tdClass}>
                    <div className="flex items-center gap-1.5">
                      <div className="w-2 h-2 rounded-full" style={{ background: SOURCE_DOT[s.source] || '#63637a' }} />
                      <span className="text-text-2">{s.source.replace('_', ' ')}</span>
                    </div>
                  </td>
                  <td className={`${tdClass} text-text-1 font-medium`}>{shortEmail(s.user_email)}</td>
                  <td className={`${tdClass} text-text-3`}>{shortRepo(s.repo_name)}</td>
                  <td className={`${tdClass} text-text-3 tabular-nums`}>
                    {new Date(s.first_seen).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                  </td>
                  <td className={`${tdClass} text-text-1 font-medium tabular-nums`}>{fmtDuration(s.duration_min)}</td>
                  <td className={`${tdClass} text-text-2 tabular-nums`}>{s.tool_call || 0}</td>
                  <td className={`${tdClass} text-accent tabular-nums`}>{s.explore || 0}</td>
                  <td className={`${tdClass} text-green tabular-nums`}>{s.edit || 0}</td>
                  <td className={`${tdClass} text-text-2 tabular-nums`}>{fmtTokens(s.output_tokens || 0)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {sessions.length >= 50 && (
          <div className="px-4 py-2 text-[10px] text-text-3 border-t border-border-dim">
            Showing top 50 of {data.sessions.length} sessions
          </div>
        )}
      </motion.div>
    </section>
  );
}
