import React, { useEffect, useMemo, useRef, useState } from "react";
import {
  PlusOutlined,
  CloseOutlined,
  FieldTimeOutlined,
  UserOutlined,
  SendOutlined,
  LoadingOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import {
  Button,
  Tooltip,
  Input,
  Form,
  Dropdown,
  Typography,
  Space,
  Spin,
} from "antd";
import { GetProp } from "antd";
import { Bubble, Sender } from "@ant-design/x";
import MarkdownViewer from "./MarkdownViewer";
import { useChat } from "@/hooks/useChat";

// bubbles角色配置
const roles: GetProp<typeof Bubble.List, "roles"> = {
  assistant: {
    placement: "start",
    avatar: undefined,
    loadingRender: () => (
      <Space>
        <Spin size="small" />
        思考中...
      </Space>
    ),
    messageRender: (content) => {
      return typeof content === "string" ? (
        <Typography className={content?.includes("```") ? "w-full" : ""}>
          <MarkdownViewer content={content} />
        </Typography>
      ) : (
        content
      );
    },
    header: <span className="text-12px text-#666">数据模型助手</span>,
  },
  user: {
    placement: "start",
    avatar: undefined,
    messageRender: (content) => {
      return <div style={{ whiteSpace: "pre-wrap" }}>{content}</div>;
    },
    styles: {
      content: {
        backgroundColor: "#d2e1fb",
      },
    },
  },
};

export default function AIChat(props: { onClose?: () => void }) {
  const [chatStarted, setChatStarted] = useState(false);
  const [inputVal, setInputVal] = useState("");
  const contentRef = useRef<HTMLDivElement>(null);
  const [contentHeight, setContentHeight] = useState(0);

  const setHeight = () => {
    setContentHeight(contentRef.current?.clientHeight || 0);
  };
  useEffect(() => {
    setHeight();
    const resizeObserver = new ResizeObserver(() => {
      setHeight();
    });
    resizeObserver.observe(contentRef.current!);
    return () => {
      resizeObserver.disconnect();
    };
  }, []);

  const { loading, onRequest, cancel, messages, setMessages, addConversation, conversationList } =
    useChat({
      app_name: "system_design",
      onSuccess: (msg) => {
        setMessages((messages) => {
          const arr = [...messages];
          // const query = arr[messages.length - 2].content as string;
          arr[messages.length - 1].status = "done";
          arr[messages.length - 1].footer = <></>;
          return arr;
        });
      },
      onUpdate: (msg) => {
        setMessages((messages) => {
          const arr = [...messages];
          arr[messages.length - 1].content += msg.answer;
          arr[messages.length - 1].id = msg.message_id;
          arr[messages.length - 1].loading = false;
          arr[messages.length - 1].status = "loading";
          return arr;
        });
      },
      onError: (error) => {
        // message.error(error.message);
        setMessages((messages) => {
          const arr = [...messages];
          arr[messages.length - 1].content = (
            <Typography.Text type="danger">{error.message}</Typography.Text>
          );
          arr[messages.length - 1].status = "error";
          arr[messages.length - 1].loading = false;
          return arr;
        });
      },
    });

  // 处理提交
  const onSubmit = (val: string) => {
    setInputVal("");
    if (val.trim()) {
      if (!chatStarted) setChatStarted(true);
    }
    if (val.trim()) {
      setMessages((prev) => [
        ...(prev || []),
        {
          id: Date.now() + "",
          role: "user",
          content: val.trim(),
          status: "done",
        },
        {
          id: Date.now() + "1",
          content: "",
          status: "loading",
          role: "assistant",
          loading: true,
        },
      ]);

      onRequest(val.trim());
    }
  };

  // 开启新的对话
  const onNewChat = () => {
    addConversation();
    setChatStarted(false);
  };

  const onStop = () => {
    cancel();
  };

  const historyItems = useMemo(() => {
    return (conversationList || []).map(item => {
      return {
        key: item.id,
        label: item.label
      }
    })
  }, [conversationList]);

  return (
    <div
      className="flex-1 h-full flex flex-col"
      style={{
        backgroundImage: "linear-gradient(137deg, #e5f4ff 0%, #efe7ff 100%)",
      }}
    >
      <div className="chat-head w-full h-40px px-10px color-#333 flex items-center justify-between">
      <span className="text-14px">
          <svg className="icon h-32px w-32px mr-4px" aria-hidden="true">
            <use xlinkHref="#icon-AI1"></use>
          </svg>
          <span>AI对话</span>
        </span>
        <span>
          <Tooltip title="新建会话">
            <Button
              type="text"
              size="small"
              icon={<PlusOutlined />}
              onClick={onNewChat}
            ></Button>
          </Tooltip>
          <Dropdown
            menu={{ items: historyItems }}
            trigger={["click"]}
            placement="bottomLeft"
            className="max-h-200px"
            arrow
          >
            <Tooltip title="历史记录">
              <Button
                type="text"
                size="small"
                icon={<FieldTimeOutlined />}
              ></Button>
            </Tooltip>
          </Dropdown>
          <Button
            type="text"
            size="small"
            icon={<CloseOutlined />}
            onClick={() => props.onClose?.()}
          ></Button>
        </span>
      </div>

      <div
        className="chat-content flex-1 px-10px overflow-hidden mt-12px"
        ref={contentRef}
        style={{ height: contentHeight }}
      >
        {!messages.length ? (
          <>
            <div className="text-center pt-200px">
              <svg className="icon h-40px! w-40px!" aria-hidden="true">
                <use xlinkHref="#icon-AI1"></use>
              </svg>
            </div>
            <h2 className="text-center">询问AI助手</h2>
            <p className="text-center">我是AI助手，有什么可以帮您的吗？</p>
          </>
        ) : (
          <div className="overflow-y-auto h-full">
            <Bubble.List
              style={{ maxHeight: contentHeight }}
              autoScroll
              items={messages}
              roles={roles}
            />
          </div>
        )}
      </div>

      <div className="px-12px py-16px">
        <Sender
          placeholder="你想咨询什么？"
          loading={loading}
          value={inputVal}
          onChange={setInputVal}
          onSubmit={onSubmit}
          onCancel={onStop}
        />
      </div>
    </div>
  );
}
