import type { UseStream } from "@langchain/langgraph-sdk/react";
import { useEffect } from "react";

import { useI18n } from "@/core/i18n/hooks";
import type { AgentThreadState } from "@/core/threads";

import { useThreadChat } from "./chats";
import { FlipDisplay } from "./flip-display";

export function ThreadTitle({
  threadId,
  thread,
  threadTitle,
}: {
  className?: string;
  threadId: string;
  thread?: UseStream<AgentThreadState>;
  threadTitle?: string;
}) {
  const { t } = useI18n();
  const { isNewThread } = useThreadChat();
  useEffect(() => {
    if (!thread) {
      return;
    }
    let _title = t.pages.untitled;

    if (thread.values?.title) {
      _title = thread.values.title;
    } else if (isNewThread) {
      _title = t.pages.newChat;
    }
    if (thread.isThreadLoading) {
      document.title = `Loading... - ${t.pages.appName}`;
    } else {
      document.title = `${_title} - ${t.pages.appName}`;
    }
  }, [
    isNewThread,
    t.pages.newChat,
    t.pages.untitled,
    t.pages.appName,
    thread,
    thread?.isThreadLoading,
    thread?.values,
  ]);

  if (threadTitle) {
    return <FlipDisplay uniqueKey={threadTitle}>{threadTitle}</FlipDisplay>;
  }
  if (!thread?.values?.title || !threadId) {
    return null;
  }
  return (
    <FlipDisplay uniqueKey={threadId}>
      {thread.values.title ?? "Untitled"}
    </FlipDisplay>
  );
}
