import { FormEvent, useEffect, useRef, useState } from 'react';
import { sendChat } from '../api';
import type { ChatMessage } from '../types';

const SYSTEM_PROMPT: ChatMessage = {
  role: 'system',
  content: 'You are a helpful assistant. Answer concisely.',
};

export function ChatTab() {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [draft, setDraft] = useState('');
  const [sending, setSending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const listRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [messages, sending]);

  async function onSubmit(event: FormEvent) {
    event.preventDefault();
    const content = draft.trim();
    if (!content || sending) return;

    const next: ChatMessage[] = [...messages, { role: 'user', content }];
    setMessages(next);
    setDraft('');
    setSending(true);
    setError(null);
    try {
      const assistant = await sendChat([SYSTEM_PROMPT, ...next]);
      setMessages([...next, assistant]);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setSending(false);
    }
  }

  return (
    <div className="tab-body">
      <div className="transcript" ref={listRef} data-testid="transcript">
        {messages.length === 0 ? <p className="empty">Ask the assistant anything to get started.</p> : null}
        {messages.map((m, idx) => (
          <article key={idx} className={`message message-${m.role}`} data-role={m.role}>
            <span className="who">{m.role === 'user' ? 'You' : 'Assistant'}</span>
            <p className="body">{m.content}</p>
          </article>
        ))}
        {sending ? (
          <article className="message message-assistant pending" data-testid="pending">
            <span className="who">Assistant</span>
            <p className="body">…</p>
          </article>
        ) : null}
      </div>

      {error ? <p className="error" data-testid="error">{error}</p> : null}

      <form className="composer" onSubmit={onSubmit}>
        <input
          value={draft}
          onChange={e => setDraft(e.target.value)}
          placeholder="Ask anything…"
          disabled={sending}
          data-testid="composer-input"
        />
        <button type="submit" disabled={sending || !draft.trim()} data-testid="composer-send">
          {sending ? 'Sending…' : 'Send'}
        </button>
      </form>
    </div>
  );
}
