import React, { useMemo } from "react";
import { Link, Navigate } from "react-router-dom";
import type { SessionSnapshot } from "../../../shared/types";
import ChatThread from "./ChatThread";
import { buildThreads, getThreadMessages } from "./utils";
import { useI18n } from "../i18n";

export default function ChatThreadScreen({
  session,
  meId,
  isBanker,
  sessionId,
  chatId,
  onSend,
}: {
  session: SessionSnapshot;
  meId: string;
  isBanker: boolean;
  sessionId: string;
  chatId: string;
  onSend: (body: string, groupId: string | null) => void;
}) {
  const { t } = useI18n();
  const threads = useMemo(() => buildThreads(session, meId, isBanker), [session, meId, isBanker]);
  const thread = threads.find((item) => item.id === chatId) ?? null;

  if (!thread) {
    return <Navigate to={`/play/${sessionId}/chat`} replace />;
  }

  const messages = getThreadMessages(session, thread.id);
  const memberCount = thread.members.length;
  const headerSub =
    thread.kind === "global"
      ? t("chat.everyone")
      : thread.kind === "direct"
      ? t("chat.directMessage")
      : memberCount === 1
      ? t("chat.memberCountOne")
      : t("chat.memberCount", { count: memberCount });

  const nameById = useMemo(() => {
    const lookup: Record<string, string> = {};
    session.players.forEach((player) => {
      lookup[player.id] = player.name;
    });
    return lookup;
  }, [session.players]);

  return (
    <div className="chat-shell">
      <div className="chat-screen chat-screen--thread">
        <header className="chat-thread-header">
          <div className="chat-thread-leading">
            <Link className="chat-back" to={`/play/${sessionId}/chat`}>
              ← {t("chat.backChats")}
            </Link>
            <div>
              <h1>{thread.name}</h1>
              <span>{headerSub}</span>
            </div>
          </div>
          <div className="chat-thread-tag">
            {thread.kind === "global"
              ? t("chat.global")
              : thread.kind === "direct"
              ? t("chat.direct")
              : t("chat.group")}
          </div>
        </header>

        <ChatThread
          thread={thread}
          messages={messages}
          meId={meId}
          nameById={nameById}
          onSend={(body) => onSend(body, thread.id === "global" ? null : thread.id)}
        />
      </div>
    </div>
  );
}
