import { useState } from 'react';
import type { Message } from '../api';
import { SourceBadge, TypeBadge } from './Badges';

export function MessageList({ messages }: { messages: Message[] }) {
  return (
    <div className="divide-y divide-border-subtle">
      {messages.map((m) => (
        <MessageRow key={m.id} message={m} />
      ))}
      {messages.length === 0 && (
        <p className="px-4 py-8 text-center text-text-muted text-sm">No messages.</p>
      )}
    </div>
  );
}

function messageSummary(m: Message): string | null {
  if (m.content) return m.content;
  if (m.msg_type === 'tool_call' && m.tool_name) {
    const inputPreview = m.tool_input
      ? `: ${typeof m.tool_input === 'string' ? m.tool_input : JSON.stringify(m.tool_input)}`.slice(0, 120)
      : '';
    return `${m.tool_name}${inputPreview}`;
  }
  if (m.msg_type === 'tool_result' && m.tool_output) {
    const status = m.tool_status ? `[${m.tool_status}] ` : '';
    return `${status}${m.tool_output.slice(0, 120)}`;
  }
  if (m.thinking) return `[thinking] ${m.thinking.slice(0, 120)}`;
  return null;
}

function MessageRow({ message: m }: { message: Message }) {
  const [expanded, setExpanded] = useState(false);
  const hasTokens = (m.input_tokens ?? 0) + (m.output_tokens ?? 0) > 0;
  const summary = messageSummary(m);

  return (
    <div
      className="px-4 py-3 hover:bg-surface-overlay cursor-pointer transition-colors"
      onClick={() => setExpanded(!expanded)}
    >
      <div className="flex items-start gap-3">
        <div className="flex items-center gap-2 shrink-0 w-48">
          <SourceBadge source={m.source} />
          <TypeBadge type={m.msg_type} />
        </div>
        <div className="flex-1 min-w-0">
          <p className={`text-sm text-text-secondary ${expanded ? '' : 'truncate'} ${!m.content && summary ? 'font-mono text-text-muted' : ''}`}>
            {summary || <span className="text-text-muted italic">no content</span>}
          </p>
        </div>
        <div className="flex items-center gap-4 shrink-0 text-xs text-text-muted">
          {hasTokens && (
            <span className="tabular-nums">
              {m.input_tokens ?? 0}↓ {m.output_tokens ?? 0}↑
            </span>
          )}
          <span className="tabular-nums">
            {m.timestamp ? new Date(m.timestamp).toLocaleTimeString() : ''}
          </span>
        </div>
      </div>

      {expanded && (
        <div className="mt-3 ml-50 space-y-2">
          {m.tool_name && (
            <div className="bg-surface-overlay rounded p-3">
              <p className="text-xs text-text-muted mb-1">Tool: {m.tool_name}</p>
              {m.tool_input != null && (
                <pre className="text-xs text-text-secondary overflow-x-auto max-h-40">
                  {String(typeof m.tool_input === 'string'
                    ? m.tool_input
                    : JSON.stringify(m.tool_input, null, 2))}
                </pre>
              )}
              {m.tool_output && (
                <div className="mt-2 border-t border-border pt-2">
                  <p className="text-xs text-text-muted mb-1">
                    Result: <span className={m.tool_status === 'success' ? 'text-success' : 'text-danger'}>{m.tool_status}</span>
                  </p>
                  <pre className="text-xs text-text-secondary overflow-x-auto max-h-40 whitespace-pre-wrap">
                    {m.tool_output.slice(0, 500)}
                    {m.tool_output.length > 500 ? '...' : ''}
                  </pre>
                </div>
              )}
            </div>
          )}
          {m.thinking && (
            <div className="bg-surface-overlay rounded p-3">
              <p className="text-xs text-text-muted mb-1">Thinking</p>
              <p className="text-xs text-text-secondary whitespace-pre-wrap max-h-40 overflow-y-auto">
                {m.thinking.slice(0, 1000)}
                {m.thinking.length > 1000 ? '...' : ''}
              </p>
            </div>
          )}
          {hasTokens && (
            <div className="flex gap-4 text-xs text-text-muted">
              <span>Input: {m.input_tokens}</span>
              <span>Output: {m.output_tokens}</span>
              <span>Cached: {m.cached_tokens}</span>
              <span>Thinking: {m.thinking_tokens}</span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
