import { useRef, useEffect, useContext } from "react";
import { RealtimeClientContext } from "../Provider/RealtimeClientProvider";
import ReactMarkdown from 'react-markdown'
import gfm from 'remark-gfm'
import { RoleType } from "@coze/api";

export default function RoomConversation() {
  const { messageList } = useContext(RealtimeClientContext);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到最新消息
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messageList]);

  return (
    <div className="flex-1 flex flex-col overflow-y-auto">
      <div className="w-full min-h-[120px] h-[120px]">
        <div className="relative h-full">
          <img src="/icons/hello.gif" alt="" className="absolute top-0  h-[97px] left-[50%] translate-x-[-50%]"/>
          <img src="/icons/conversation-bg.png" alt="background" className='w-[222px] h-[49px] absolute bottom-0 left-[50%] translate-x-[-50%]'/>
          <div className="text-black text-[14px] absolute bottom-[22px] left-[50%] translate-x-[-50%] z-[10]">Hey，我是您的六纬AI填报师</div>
        </div>
      </div>
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messageList.map((message: any, index: number) => (
          <div
            key={index}
            className={`flex ${
              message.role === RoleType.Assistant
                ? "justify-start"
                : "justify-end"
            }`}
          >
            <div  
              className={`max-w-3/4 p-3 rounded-lg ${
                message.role === RoleType.Assistant
                  ? "bg-white text-black rounded-tl-none"
                  : "bg-blue-500 text-white rounded-tr-none"
              }`}
            >
              <ReactMarkdown remarkPlugins={[gfm]}>{message.content}</ReactMarkdown>
            </div>
          </div>
        ))}

        <div ref={messagesEndRef} />
      </div>
    </div>
  );
}
