import { useMemo, useState } from 'react';
import { useMessages } from '../hooks/use-messages';
import { useMembers } from '../hooks/use-members';
import { Composer } from './composer';
import { MessageItem } from './message-item';
import { ConversationSettings } from './conversation-settings';
import type { Conversation } from '../types';

/**
 * The main conversation view: top-level messages + composer. Replies (messages with a
 * parentInteractionId) are hidden here and live in the ThreadPane — a message with replies shows a
 * "N replies" link that opens it. @mentions, reactions, and attachments all work.
 */
export function Thread({
  threadId,
  conversation,
  activeRootId,
  onOpenThread,
  onLeft,
}: {
  threadId: string | null;
  conversation?: Conversation | null;
  activeRootId?: string | null;
  onOpenThread?: (rootId: string) => void;
  onLeft?: () => void;
}) {
  const { messages, loading, error, send, react, upload, typingUserIds, seenIds, sendTyping, canReact, canUpload } = useMessages(threadId);
  const members = useMembers(threadId);
  const memberNames = useMemo(() => members.map((m) => m.name), [members]);
  const [settingsOpen, setSettingsOpen] = useState(false);

  const membership = conversation?.membership;
  const manageable = membership === 'group' || membership === 'channel';

  const topLevel = useMemo(() => messages.filter((m) => !m.parentInteractionId), [messages]);
  const replyCount = useMemo(() => {
    const counts = new Map<string, number>();
    for (const m of messages) if (m.parentInteractionId) counts.set(m.parentInteractionId, (counts.get(m.parentInteractionId) ?? 0) + 1);
    return counts;
  }, [messages]);

  if (!threadId) {
    return <div className="miu-empty miu-thread-empty">Select a conversation.</div>;
  }

  return (
    <div className={`miu-thread${activeRootId ? ' has-pane' : ''}`}>
      {conversation ? (
        <div className="miu-thread-head">
          <span className="miu-thread-title">
            {membership === 'channel' ? '# ' : ''}
            {conversation.title || 'Conversation'}
          </span>
          {manageable ? (
            <button type="button" className="miu-thread-settings" title="Settings" aria-label="Conversation settings" onClick={() => setSettingsOpen(true)}>
              ⚙
            </button>
          ) : null}
        </div>
      ) : null}
      <div className="miu-messages">
        {loading && messages.length === 0 ? <div className="miu-empty">Loading…</div> : null}
        {error ? <div className="miu-empty miu-error">{error}</div> : null}
        {topLevel.map((m) => (
          <MessageItem
            key={m.id}
            message={m}
            memberNames={memberNames}
            canReact={canReact}
            onReact={(id, emoji) => void react(id, emoji)}
            seen={seenIds.has(m.id)}
            replyCount={replyCount.get(m.id) ?? 0}
            {...(onOpenThread ? { onOpenThread } : {})}
          />
        ))}
        {typingUserIds.length > 0 ? (
          <div className="miu-typing">{typingUserIds.length === 1 ? 'typing…' : 'several people are typing…'}</div>
        ) : null}
      </div>

      <Composer members={members} canUpload={canUpload} upload={upload} onSend={send} onTyping={sendTyping} />

      {settingsOpen && manageable && conversation ? (
        <ConversationSettings
          threadId={conversation.threadId}
          title={conversation.title || ''}
          membership={membership as 'group' | 'channel'}
          onClose={() => setSettingsOpen(false)}
          {...(onLeft ? { onLeft } : {})}
        />
      ) : null}
    </div>
  );
}
