import { useCallback, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api, type Session } from '../api';
import { usePolling } from '../hooks/usePolling';
import { SourceBadge } from './Badges';
import { KNOWN_SOURCES } from '../sources';

const PAGE_SIZE = 50;

export function SessionsTable() {
  const [source, setSource] = useState('all');
  const [offset, setOffset] = useState(0);
  const navigate = useNavigate();

  const fetcher = useCallback(
    () => api.sessions({ source: source === 'all' ? undefined : source, limit: PAGE_SIZE, offset }),
    [source, offset],
  );
  const { data, error, loading } = usePolling<Session[]>(fetcher, 5000);

  const handleSourceChange = (s: string) => {
    setSource(s);
    setOffset(0);
  };

  return (
    <div className="bg-surface-raised border border-border rounded-lg overflow-hidden">
      <div className="px-4 py-3 border-b border-border flex items-center justify-between">
        <h2 className="text-sm font-semibold text-text-primary">Sessions</h2>
        <div className="flex gap-1">
          {['all', ...KNOWN_SOURCES].map((s) => (
            <button
              key={s}
              onClick={() => handleSourceChange(s)}
              className={`text-xs px-2 py-1 rounded transition-colors ${
                source === s
                  ? 'bg-accent text-text-inverse'
                  : 'text-text-secondary hover:text-text-primary hover:bg-surface-overlay'
              }`}
            >
              {s === 'all' ? 'All' : s.replaceAll('_', ' ')}
            </button>
          ))}
        </div>
      </div>

      {loading && <p className="p-4 text-text-muted text-sm">Loading...</p>}
      {error && <p className="p-4 text-danger text-sm">Error: {error}</p>}

      <div className="overflow-x-auto">
      <table className="w-full text-sm min-w-[1000px]">
        <thead>
          <tr className="text-left text-xs text-text-muted uppercase tracking-wide border-b border-border">
            <th className="px-4 py-2">Source</th>
            <th className="px-4 py-2">Session ID</th>
            <th className="px-4 py-2">Org</th>
            <th className="px-4 py-2">User</th>
            <th className="px-4 py-2">Repo</th>
            <th className="px-4 py-2">Branch</th>
            <th className="px-4 py-2">CWD</th>
            <th className="px-4 py-2">Model</th>
            <th className="px-4 py-2 text-right">Messages</th>
            <th className="px-4 py-2 text-right">Last Active</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-border-subtle">
          {data?.map((s) => (
            <tr
              key={s.id}
              onClick={() => navigate(`/sessions/${encodeURIComponent(s.id)}`)}
              className="hover:bg-surface-overlay cursor-pointer transition-colors"
            >
              <td className="px-4 py-2.5">
                <SourceBadge source={s.source} />
              </td>
              <td className="px-4 py-2.5 text-text-secondary font-mono text-xs truncate max-w-xs">
                {s.id}
              </td>
              <td className="px-4 py-2.5 text-text-secondary text-xs">
                {s.org ?? <span className="text-text-muted">—</span>}
              </td>
              <td className="px-4 py-2.5 text-text-secondary text-xs truncate max-w-[10rem]">
                {s.user_email ?? s.device_name ?? <span className="text-text-muted">—</span>}
              </td>
              <td className="px-4 py-2.5 text-text-secondary text-xs truncate max-w-[10rem]">
                {s.repo_name ?? s.project_hash?.slice(0, 8) ?? <span className="text-text-muted">—</span>}
              </td>
              <td className="px-4 py-2.5 text-text-secondary text-xs">
                {s.git_branch ?? <span className="text-text-muted">—</span>}
              </td>
              <td className="px-4 py-2.5 text-text-secondary text-xs font-mono truncate max-w-[12rem]">
                {s.cwd ?? <span className="text-text-muted">—</span>}
              </td>
              <td className="px-4 py-2.5 text-text-secondary">
                {s.model ?? <span className="text-text-muted">—</span>}
              </td>
              <td className="px-4 py-2.5 text-right tabular-nums text-text-secondary">
                {s.message_count}
              </td>
              <td className="px-4 py-2.5 text-right text-text-muted text-xs">
                {s.latest_message ? new Date(s.latest_message).toLocaleString() : '—'}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      </div>

      {data?.length === 0 && !loading && (
        <p className="px-4 py-8 text-center text-text-muted text-sm">No sessions found.</p>
      )}

      {data && data.length > 0 && (
        <div className="px-4 py-3 border-t border-border flex items-center justify-between">
          <button
            onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
            disabled={offset === 0}
            className="text-xs px-3 py-1.5 rounded bg-surface-overlay text-text-secondary disabled:opacity-40 disabled:cursor-not-allowed hover:bg-border transition-colors"
          >
            Previous
          </button>
          <span className="text-xs text-text-muted">
            Showing {offset + 1}–{offset + (data?.length ?? 0)}
          </span>
          <button
            onClick={() => setOffset(offset + PAGE_SIZE)}
            disabled={(data?.length ?? 0) < PAGE_SIZE}
            className="text-xs px-3 py-1.5 rounded bg-surface-overlay text-text-secondary disabled:opacity-40 disabled:cursor-not-allowed hover:bg-border transition-colors"
          >
            Next
          </button>
        </div>
      )}
    </div>
  );
}
