import { Attachments, Bubble, BubbleProps } from "@ant-design/x"
import { Avatar, Button, message, Tooltip, Typography } from "antd"
import { useMemo, useRef, useEffect, useState } from "react"
import markdownit from "markdown-it"
import { throttle } from "@/utils/tools"
import user from "@/assets/images/user.jpg"
import { observer } from "@/stores/utils"
import "./index.scss"

const md = markdownit({ html: true, breaks: true })

interface IProps {
  showUserInfo?: boolean
  showPlaceholderNode?: boolean
  botInfo: any
  streamingChat: (content: string) => void
  messageList: any[]
  deleteMessage: (id: string) => void
  reGenerate: () => void
  getMessageList?: () => void
  chatId: string
  isLoading: boolean
  abortChat: () => void
  containerRef: any
  conversationID: string
  scrollToBottom: () => void
}
const MessageList = (props: IProps) => {
  const [isAtBottom, setIsAtBottom] = useState(true)
  const lastScrollTop = useRef(false)
  const [messageApi, contextHolder] = message.useMessage()
  const {
    botInfo,
    streamingChat,
    messageList,
    deleteMessage,
    reGenerate,
    getMessageList,
    chatId,
    isLoading,
    abortChat,
    containerRef,
    conversationID,
    scrollToBottom,
    showUserInfo,
    showPlaceholderNode,
  } = props

  useEffect(() => {
    setIsAtBottom(true)
  }, [conversationID])

  useEffect(() => {
    if (containerRef.current?.nativeElement) {
      const throttledScroll = throttle(handleScroll, 100)
      containerRef.current?.nativeElement.addEventListener(
        "scroll",
        throttledScroll
      )
      return () => {
        containerRef.current?.nativeElement.removeEventListener(
          "scroll",
          throttledScroll
        )
      }
    }
  }, [])

  const handleScroll = (e: any) => {
    const ele = e.target
    if (ele.scrollTop + ele.clientHeight >= ele.scrollHeight - 5) {
      setIsAtBottom(true)
    } else {
      setIsAtBottom(false)
    }
    if (getMessageList) {
      if (
        ele.scrollTop < lastScrollTop.current &&
        ele.scrollTop <= 50 &&
        !isLoading
      ) {
        getMessageList()
      }
      lastScrollTop.current = ele.scrollTop
    }
  }

  const renderMarkdown: BubbleProps["messageRender"] = (content) => (
    <Typography>
      <div
        className="message_content"
        dangerouslySetInnerHTML={{ __html: md.render(content) }}
      />
    </Typography>
  )

  const renderUserBubble = (bubbleData: any) => {
    return (
      <div className="flex_column flex_end">
        {bubbleData.file_url?.map(
          (file: { id: string; name: string; path: string }) => {
            return (
              <Attachments.FileCard
                className="file_card"
                key={file.path}
                item={{
                  uid: file.id,
                  name: file.name,
                  url: file.path,
                }}
              />
            )
          }
        )}
        <div className="message_content">{bubbleData.content}</div>
      </div>
    )
  }

  const renderAssistantFooter = (bubbleData: any, index: number) => {
    const lastMessage = index === messageList.length - 1
    if (bubbleData.prologue && messageList.length === 1) {
      return (
        <div className="flex_wrap">
          {botInfo?.suggestedQuestions &&
            botInfo?.suggestedQuestions.map((item: any) => {
              return (
                <div
                  className="csp operate_btn"
                  key={item}
                  onClick={() => streamingChat(item)}
                >
                  {item}
                </div>
              )
            })}
        </div>
      )
    }
    if (!bubbleData.is_answer && !bubbleData.prologue) {
      return (
        <div className="flex_left">
          <Tooltip title="复制">
            {contextHolder}
            <div
              className="mesage_btn"
              onClick={async () => {
                await navigator.clipboard.writeText(String(bubbleData.content))
                messageApi.success("复制成功!")
              }}
            >
              <i className="iconfont icon-fuzhi1"></i>
            </div>
          </Tooltip>
          {lastMessage && (
            <Tooltip title="重新生成">
              <div className="mesage_btn" onClick={reGenerate}>
                <i className="iconfont icon-zhongxinfenxi"></i>
              </div>
            </Tooltip>
          )}
          {bubbleData.id && (
            <Tooltip title="删除">
              <div
                className="mesage_btn"
                onClick={() => {
                  bubbleData.id && deleteMessage(bubbleData.id)
                }}
              >
                <i className="iconfont icon-shanchu"></i>
              </div>
            </Tooltip>
          )}
        </div>
      )
    }
  }
  const getRoles = (bubbleData: any, index: number) => {
    bubbleData.role = bubbleData.role ? bubbleData.role : "assistant"
    switch (bubbleData.role) {
      case "user":
        return {
          placement: "end" as const,
          className: "user_bubble",
          variant: "borderless" as const,
          header: () => {
            if (showUserInfo) {
              return <div className="fs-12 secondaryTextColor">user</div>
            }
          },
          avatar: showUserInfo ? <Avatar size="large" src={user} /> : undefined,
          messageRender: () => renderUserBubble(bubbleData),
        }
      case "assistant":
        return {
          placement: "start" as const,
          className: "assistant_bubble",
          variant: "borderless" as const,
          typing: bubbleData.is_answer ? { step: 5, interval: 20 } : false,
          messageRender: (content: string) => {
            // 检查是否为答题卡类型
            if (bubbleData.content_type === "card" && bubbleData.card_content) {
              const cardData = bubbleData.card_content
              const lastMessage = index === messageList.length - 1
              console.log("🃏 渲染答题卡:", cardData)
              
              return (
                <div className="flex_column">
                  {content && renderMarkdown(content)}
                  <div className="card_message message_content">
                    <div
                      className="fs-18"
                      dangerouslySetInnerHTML={{
                        __html: (cardData.Title || cardData.title || "题目").replace(/\n/g, "<br />"),
                      }}
                    ></div>
                    {(cardData.Options || cardData.options || []).map((item: { name: string } | string, idx: number) => {
                      const optionText = typeof item === 'string' ? item : item.name
                      return (
                        <div
                          className={`card_item ${
                            lastMessage ? "" : "disabled"
                          }`}
                          key={idx}
                          onClick={() => {
                            if (lastMessage) {
                              console.log("🔄 用户选择选项:", optionText)
                              streamingChat(optionText)
                            }
                          }}
                        >
                          {optionText}
                        </div>
                      )
                    })}
                  </div>
                </div>
              )
            } else {
              return renderMarkdown(content)
            }
          },
          loadingRender: () => {
            return (
              <div className="message_content">
                <span className="ant-bubble-dot">
                  <i className="ant-bubble-dot-item"></i>
                  <i className="ant-bubble-dot-item"></i>
                  <i className="ant-bubble-dot-item"></i>
                </span>
              </div>
            )
          },
          header: () => {
            if (showUserInfo) {
              return (
                <div className="fs-12 secondaryTextColor">{botInfo?.name}</div>
              )
            }
          },
          avatar: showUserInfo ? (
            <Avatar size="large" src={botInfo?.icon_url} />
          ) : undefined,
          footer: <>{renderAssistantFooter(bubbleData, index)}</>,
        }
      default:
        return {}
    }
  }
  const placeholderNode = botInfo?.name && (
    <div className="example_item">
      <div className="example_content">
        <div className="example_title">{botInfo?.name}</div>
        <div className="example_desc">{botInfo?.description}</div>
      </div>
      <p className="example_tips">试试这些例子...</p>
      <div className="flex_wrap">
        {botInfo?.suggestedQuestions &&
          botInfo?.suggestedQuestions.map((item: any) => {
            return (
              <div
                className="ask_item csp"
                key={item}
                onClick={() => streamingChat(item)}
              >
                {item}
              </div>
            )
          })}
      </div>
    </div>
  )
  const list = messageList.slice().reverse()
  const bubbleItems = showPlaceholderNode
    ? list.length > 0
      ? list
      : [
          {
            key: "top",
            role: "assets",
            content: placeholderNode,
            variant: "borderless",
          },
        ]
    : list

  return (
    <>
      <Bubble.List
        id="BubbleList"
        ref={containerRef}
        className="bubble_list"
        roles={getRoles}
        items={bubbleItems}
      />
      <div className="operate_wrap">
        <div className="operate_box">
          {isLoading && chatId && (
            <div className=" flex_c mb-20">
              <Button className="abord_btn" onClick={abortChat}>
                <i className="iconfont icon-jieshuluyin"></i>停止响应
              </Button>
            </div>
          )}
          <div
            className="to_bottom"
            style={{ display: isAtBottom ? "none" : "flex" }}
            onClick={scrollToBottom}
          >
            <svg
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M12 21C11.7348 21 11.4804 20.8946 11.2929 20.7071L4.29289 13.7071C3.90237 13.3166 3.90237 12.6834 4.29289 12.2929C4.68342 11.9024 5.31658 11.9024 5.70711 12.2929L11 17.5858V4C11 3.44772 11.4477 3 12 3C12.5523 3 13 3.44772 13 4V17.5858L18.2929 12.2929C18.6834 11.9024 19.3166 11.9024 19.7071 12.2929C20.0976 12.6834 20.0976 13.3166 19.7071 13.7071L12.7071 20.7071C12.5196 20.8946 12.2652 21 12 21Z"
                fill="currentColor"
              ></path>
            </svg>
          </div>
        </div>
      </div>
    </>
  )
}

export default observer(MessageList)
