import React, { useEffect, useState, useRef } from "react";
import { useSessionStorage } from "react-use";
import * as coursesAPI from "../../apis/coursesAPI";
import moment from "moment";
import { useParams, useNavigate } from "react-router-dom";

import { message } from "antd";

const InteractiveArea = ({ h5courseCode }) => {
  const [interactiveList, setInteractiveList] = useState([]);
  const [inputValue, setInputValue] = useState("");
  const [isInit, setIsInit] = useState(true);
  const [isTourist, setIsTourist] = useState(false);
  const { courseCode, token } = useParams();

  const chatRef = useRef(null);
  const guid = generateGUID();
  if (h5courseCode) {
    console.log("%c Line:19 🥟 h5courseCode", "color:#f5ce50", h5courseCode);
    sessionStorage.setItem("courseCode", h5courseCode);
  } else {
    sessionStorage.setItem("courseCode", courseCode);
    if (token) {
      sessionStorage.setItem("token", JSON.stringify(token));
    }
  }

  useEffect(() => {
    getUserInfo();
  }, [isInit]);
  //   useEffect(() => {},[isTourist]);
  useEffect(() => {
    //       const chatBox = document.getElementById("chat-box");
    //   chatBox.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });

    const intervalId = setInterval(initFetchData, 5000);
    return () => clearInterval(intervalId);
  }, [interactiveList, inputValue]);

  function generateGUID() {
    const s4 = () =>
      (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
  }
  const getUserInfo = async () => {
    if (sessionStorage.getItem("token") !== "null") {
      const userInfo = await coursesAPI.getUserInfo();
      sessionStorage.setItem("userCode", userInfo?.UserCode);
      sessionStorage.setItem("userName", userInfo?.UserName);
    } else {
      sessionStorage.setItem("userCode", guid);
      sessionStorage.setItem("userName", guid.substring(0, 6));
      setIsTourist(true);
    }
    initFetchData();
  };

  const initFetchData = async () => {
    let result;
    if (sessionStorage.getItem("token") !== "null") {
      result = await coursesAPI.getChatMessagePagesAsync(
        sessionStorage.getItem("courseCode")
      );
    } else {
      result = await coursesAPI.getChatMessagePagesVisitorAsync(
        sessionStorage.getItem("courseCode")
      );
    }

    let initList = [];
    if (result && result.result && result.result.PageData) {
      // 初始化
      if (isInit) {
        for (let i of result.result.PageData) {
          if (i.UserCode === sessionStorage.getItem("userCode")) {
            initList.unshift({
              isMyMessage: true,
              code: i.Code,
              content: i.Content,
              createTime: dateTime(i.CreateTime),
              userCode: i.UserCode,
              avage: i.HeadImg,
              name: i.DisplayName,
            });
          } else {
            initList.unshift({
              isMyMessage: false,
              code: i.Code,
              content: i.Content,
              createTime: dateTime(i.CreateTime),
              userCode: i.UserCode,
              avage: i.HeadImg,
              name: i.DisplayName || i.Visitor.substring(0, 6),
            });
          }
        }
        if (initList.length !== 0) {
          setInteractiveList(initList);
        }
      } else {
        const newList = result.result.PageData.reduce(
          (list, item) => {
            let exists;
            if (isTourist) {
              exists = interactiveList.find(
                (i) =>
                  i.code === item.Code ||
                  item.Visitor === sessionStorage.getItem("userCode")
              );
            } else {
              exists = interactiveList.find(
                (i) =>
                  i.code === item.Code ||
                  item.UserCode === sessionStorage.getItem("userCode")
              );
            }
            if (!exists) {
              list.push({
                isMyMessage: false,
                code: item.Code,
                content: item.Content,
                createTime: item.CreateTime,
                userCode: item.UserCode,
                avage: item.HeadImg,
                name: item.DisplayName,
              });
            }
            return list;
          },
          [...interactiveList]
        );
        setInteractiveList(newList);
      }
    }
    setIsInit(false);
  };

  const dateTime = (startTime) => {
    const dateObj = moment(startTime).local();
    const formattedTime = dateObj.format("YYYY-MM-DD HH:mm:ss");
    return formattedTime;
  };

  const inputOnchange = (event) => {
    setInputValue(event.target.value);
  };

  return (
    <div className="w-full h-screen bg-gray-200 p-4 flex flex-col">
      {/* 聊天记录 */}
      <div className="flex-grow overflow-y-auto" id="chat-box" ref={chatRef}>
        {/* 接收到的消息 */}
        {interactiveList.map((item) =>
          item.isMyMessage ? (
            <div className="flex items-start justify-end mb-4">
              <div className="text-right">
                <p className="font-bold">
                  {item.name || item.userCode.substring(0, 6)}
                </p>
                <p className="bg-blue-500 rounded-lg px-4 py-2 text-white">
                  {item.content}
                </p>
                <p className="text-gray-600 text-sm mt-1">{item.createTime}</p>
              </div>
              <img
                src={item.avage || process.env.PUBLIC_URL + "/teacher.webp"}
                alt="Your avatar"
                className="rounded-full w-12 h-12 ml-3"
              />
            </div>
          ) : (
            <div className="flex items-start mb-4">
              <img
                src={process.env.PUBLIC_URL + "/otherImage.jpg"}
                alt="User avatar"
                className="rounded-full w-12 h-12 mr-3"
              />
              <div>
                <p className="font-bold">{item.name}</p>
                <p className="bg-gray-300 rounded-lg px-4 py-2">
                  {item.content}
                </p>
                <p className="text-gray-600 text-sm mt-1">{item.createTime}</p>
              </div>
            </div>
          )
        )}
      </div>

      {/* 输入框及发送按钮 */}
      <div className="pt-2 pb-4">
        <div className="relative flex items-center">
          <input
            type="text"
            placeholder="发送信息"
            className="flex-grow bg-white rounded-l-lg px-4 py-2 shadow-md focus:outline-none"
            onChange={inputOnchange}
            style={{ width: "100px" }}
            value={inputValue}
          />
          <button
            className="bg-blue-500 text-white font-bold py-2 px-5 rounded-r-lg focus:outline-none"
            onClick={() => {
              if (inputValue.trim()) {
                let lista = interactiveList;
                lista.push({
                  isMyMessage: true,
                  content: inputValue,
                  createTime: dateTime(new Date()),
                  userCode: sessionStorage.getItem("userCode"),
                  avage: null,
                  name: sessionStorage.getItem("userName"),
                });
                if (isTourist) {
                  coursesAPI.sendVisitChatMessageAsync(
                    inputValue,
                    sessionStorage.getItem("courseCode"),
                    sessionStorage.getItem("userCode")
                  );
                } else {
                  coursesAPI.sendChatMessageAsync(
                    inputValue,
                    sessionStorage.getItem("courseCode")
                  );
                }
              } else {
                message.error("发送框不能为空");
              }
              setInputValue("");
            }}
          >
            发送
          </button>
        </div>
      </div>
    </div>
  );
};

export default InteractiveArea;
