import { useParams } from 'react-router';
import { Activity, Loader2, Radio } from 'lucide-react';
import { DataList, DataRow, EmptyBlock, ErrorBlock, LoadingBlock, MetaItem } from '@/components/Data';
import { useLiveSessions } from 'state/useLiveSessions';
import { chatSessionPath } from './chat-routes';

/**
 * What the agent is actually running, as opposed to what it has ever run.
 *
 * The list below this one reads transcripts from disk — history, and thousands of it. This reads the
 * agent's in-memory map over the sidecar protocol, so it is the only view that can tell you a
 * conversation is still working while nothing is on screen. That distinction is the whole point: after
 * a `pm2 restart officer`, or from a browser that has never seen the session, officer itself has no
 * record of a live turn and only the agent can say.
 */
export const LiveSessions = () => {
  // Only to highlight the row you already have open; the titles come from the server now.
  const { sessionId } = useParams<{ sessionId: string }>();
  const { live, isLoading, error, refetch } = useLiveSessions();

  if (isLoading && live.length === 0) return <LoadingBlock label="Asking the agent…" />;
  if (error) {
    return (
      <ErrorBlock
        title="Could not reach the agent"
        message="The sidecar did not answer. Nothing is necessarily wrong with a running session — this view just cannot see it."
        action={
          <button onClick={() => refetch()} className="cursor-pointer text-sm underline">
            Try again
          </button>
        }
      />
    );
  }

  if (live.length === 0) {
    return <EmptyBlock icon={Radio} title="Nothing running" hint="Sessions with a live agent appear here." />;
  }

  return (
    <DataList>
      {live.map((session) => {
        // The route opens Claude's id, not the agent's session key — they are different things and only
        // the agent holds the mapping. No id yet means a conversation whose first turn has not landed:
        // shown, but deliberately not a link, since there is nothing to open.
        const transcriptId = session.claudeSessionId;

        return (
          <DataRow
            key={session.sessionKey}
            to={transcriptId ? chatSessionPath(transcriptId) : undefined}
            selected={transcriptId === sessionId}
            title={session.title ?? 'Starting…'}
            meta={[
              session.isGenerating ? (
                <MetaItem key="g" icon={Loader2}>
                  <span className="text-duck-teal">generating</span>
                </MetaItem>
              ) : (
                <span key="g" className="text-muted-foreground">
                  idle
                </span>
              ),
              // The field worth surfacing: it is what keeps a session alive with nothing on screen, and
              // what makes it unsafe to restart the agent sidecar.
              session.pendingTasks > 0 ? (
                <MetaItem key="t" icon={Activity}>
                  {session.pendingTasks} background task{session.pendingTasks === 1 ? '' : 's'}
                </MetaItem>
              ) : null,
            ]}
          />
        );
      })}
    </DataList>
  );
};
