import React, { useCallback, useEffect, useState } from "react";

import classNames from "classnames";
import { useDispatch, useSelector } from "react-redux";

import { setHidePopup, setShowPopup } from "../../../actions/commonActions";
import CustomImage from "../../../components/CustomImage/CustomImage";
import TButton from "../../../components/TButton/TButton";
import TPopUp from "../../../components/TPopUp/TPopUp";
import TQRCode from "../../../components/TQRCode/TQRCode";
import { ACTIVE_POPUP } from "../../../utils/Config";
import { $L } from "../../../utils/helperMethods";
import css from "./PlayerOverlayChat.module.less";

export default function PlayerOverlayChat({
  currentTime,
  videoVerticalVisible,
  imageQRCodeUrl,
  QRCodeUrl,
}) {
  const dispatch = useDispatch();
  const chatData = useSelector((state) => state.play.chatData);
  const [recentChats, setRecentChats] = useState([]);
  const { popupVisible, activePopup } = useSelector(
    (state) => state.common.popup
  );

  const handleQRCodeClick = useCallback(() => {
    dispatch(setShowPopup(ACTIVE_POPUP.qrPopup));
  }, [dispatch]);

  const onClose = useCallback(() => {
    dispatch(setHidePopup());
  }, [dispatch]);

  const filterAndSelectRecentChat = useCallback(() => {
    return (
      chatData &&
      chatData.length > 0 &&
      chatData
        .filter((item) => currentTime * 1000 >= item.offset)
        .sort((a, b) => b.offset - a.offset)
        .slice(0, videoVerticalVisible ? 4 : 3)
    );
  }, [chatData, currentTime, videoVerticalVisible]);

  useEffect(() => {
    const filteredChats = filterAndSelectRecentChat();
    setRecentChats(filteredChats);
  }, [currentTime, chatData]);

  return (
    <>
      {chatData && Object.keys(chatData).length > 0 && (
        <div
          className={classNames(
            css.chatContainer,
            videoVerticalVisible && css.verticalChat
          )}
        >
          <div className={css.chatHeader} aria-label="LIVE CHAT">
            {$L("LIVE CHAT")}
          </div>
          <div
            className={classNames(
              css.contents,
              videoVerticalVisible && css.verticalContent
            )}
          >
            {recentChats &&
              recentChats.length > 0 &&
              recentChats.map((item, index) => (
                <div
                  key={index}
                  className={css.chatItem}
                  style={{ order: -index }}
                >
                  <div className={css.username} aria-label={item?.username}>
                    {item?.username}
                  </div>
                  <div className={css.content} aria-label={item?.content}>
                    {item?.content}
                  </div>
                </div>
              ))}
          </div>
          {(imageQRCodeUrl || QRCodeUrl) && !videoVerticalVisible && (
            <TButton
              className={css.messageBtn}
              onClick={handleQRCodeClick}
              ariaLabel="TYPE A MESSAGE"
            >
              {"TYPE A MESSAGE"}
            </TButton>
          )}
          {!videoVerticalVisible && (
            <p className={css.chatclose} aria-label="chat close, button">
              X
            </p>
          )}
        </div>
      )}
      {activePopup === ACTIVE_POPUP.qrPopup && (
        <TPopUp kind="qrPopup" open={popupVisible} onClose={onClose}>
          <div className={css.popupContainer}>
            <div className={css.header}>
              <h3 aria-label="QR CODE Heading 1">{$L("QR CODE")}</h3>
            </div>

            <div className={css.qrcodeContainer}>
              <div className={css.qrcode} aria-label="QR image">
                {imageQRCodeUrl ? (
                  <CustomImage src={imageQRCodeUrl} />
                ) : (
                  <TQRCode text={QRCodeUrl} width="360" height="360" />
                )}
              </div>
              <h3 aria-label="To send a message, please scan the QR code.">
                {$L("To send a message, please scan the QR code.")}
              </h3>
              <TButton
                className={css.popupBtn}
                onClick={onClose}
                ariaLabel="Close"
              >
                {$L("CLOSE")}
              </TButton>
            </div>
          </div>
        </TPopUp>
      )}
    </>
  );
}
