import { useCallback } from 'react';
import { useParams, Link } from 'react-router-dom';
import { api, type Session, type Message } from '../api';
import { usePolling } from '../hooks/usePolling';
import { MessageList } from '../components/MessageList';
import { SourceBadge } from '../components/Badges';

function ContextRow({ label, value }: { label: string; value: string | null | undefined }) {
  if (!value) return null;
  return (
    <div className="flex items-baseline gap-2">
      <span className="text-xs text-text-muted w-20 shrink-0">{label}</span>
      <span className="text-xs text-text-secondary font-mono truncate">{value}</span>
    </div>
  );
}

export function SessionDetail() {
  const { id } = useParams<{ id: string }>();
  const sessionId = decodeURIComponent(id ?? '');

  const sessionFetcher = useCallback(
    () => api.session(sessionId),
    [sessionId],
  );
  const { data: session } = usePolling<Session | null>(sessionFetcher, 5000);

  const messageFetcher = useCallback(
    () => api.messages(sessionId, { limit: 200 }),
    [sessionId],
  );
  const { data, error, loading } = usePolling<Message[]>(messageFetcher, 3000);

  const hasContext = session && (session.user_email || session.repo_name || session.project_hash || session.device_name || session.org);

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <Link
          to="/sessions"
          className="text-sm text-accent hover:text-accent-hover"
        >
          &larr; Sessions
        </Link>
        <h2 className="text-sm font-mono text-text-secondary truncate">{sessionId}</h2>
      </div>

      {session && (
        <div className="bg-surface-raised border border-border rounded-lg overflow-hidden">
          <div className="px-4 py-3 border-b border-border">
            <h3 className="text-sm font-semibold text-text-primary">Session Info</h3>
          </div>
          <div className="px-4 py-3 grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="space-y-1.5">
              <div className="flex items-center gap-2">
                <SourceBadge source={session.source} />
                {session.model && (
                  <span className="text-xs text-text-muted">{session.model}</span>
                )}
              </div>
              <ContextRow label="Org" value={session.org} />
              <ContextRow label="User" value={session.user_email} />
              <ContextRow label="Name" value={session.user_name} />
              <ContextRow label="Device" value={session.device_name} />
            </div>
            <div className="space-y-1.5">
              <ContextRow label="Repo" value={session.repo_name} />
              <ContextRow label="Branch" value={session.git_branch} />
              <ContextRow label="Commit" value={session.git_commit?.slice(0, 10)} />
              <ContextRow label="URL" value={session.repo_url} />
            </div>
            <div className="space-y-1.5">
              <ContextRow label="CWD" value={session.cwd} />
              <ContextRow label="Hash" value={session.project_hash} />
              {!hasContext && (
                <span className="text-xs text-text-muted italic">No session context available</span>
              )}
            </div>
          </div>
        </div>
      )}

      <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">
          <h3 className="text-sm font-semibold text-text-primary">Messages</h3>
          <span className="text-xs text-text-muted">
            {loading ? 'loading...' : `${data?.length ?? 0} messages`}
          </span>
        </div>
        {error && <p className="p-4 text-danger text-sm">Error: {error}</p>}
        {data && <MessageList messages={data} />}
      </div>
    </div>
  );
}
