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

export default function ChatListScreen({
  session,
  meId,
  isBanker,
  sessionId,
  backHref,
  unreadIds,
}: {
  session: SessionSnapshot;
  meId: string;
  isBanker: boolean;
  sessionId: string;
  backHref: string;
  unreadIds: Set<string>;
}) {
  const { t } = useI18n();
  const [query, setQuery] = useState("");
  const threads = useMemo(() => buildThreads(session, meId, isBanker), [session, meId, isBanker]);
  const filtered = threads.filter((thread) =>
    thread.name.toLowerCase().includes(query.trim().toLowerCase()),
  );
  const list = query.trim() ? filtered : threads;
  const conversationLabel =
    threads.length === 1
      ? t("chat.conversationCountOne")
      : t("chat.conversationCount", { count: threads.length });

  return (
    <div className="chat-shell">
      <div className="chat-screen">
        <header className="chat-screen-header">
          <Link className="chat-back" to={backHref}>
            ← {t("chat.back")}
          </Link>
          <div className="chat-screen-title">
            <h1>{t("chat.title")}</h1>
            <span>{conversationLabel}</span>
          </div>
        </header>

        <div className="chat-search">
          <input
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder={t("chat.searchPlaceholder")}
          />
        </div>

        <ChatList threads={list} basePath={`/play/${sessionId}/chat`} unreadIds={unreadIds} />

        <Link
          className="chat-fab"
          to={`/play/${sessionId}/chat/new`}
          aria-label={t("chat.newTitle")}
        >
          +
        </Link>
      </div>
    </div>
  );
}
