import { ReactComponent as ThreeDotIcon } from "../../../../../assets/treedotIcon.svg";
import { ReactComponent as TreadChatIcon } from "../../../../../assets/treadChatIcon.svg";
import PinnedIcon from "../../../../../assets/pinedIcon.svg";
import UnpinIcon from "../../../../../assets/unpinedIcon.svg";
import "./ChatDefaultMessageType.styles.scss";
import CheckBlueIcon from "../../../../../assets/checkBlueIcon.svg";
import WarningRedIcon from "../../../../../assets/warningRedIcon.svg";
import ThumbsUpYellowIcon from "../../../../../assets/thumbsUpYellowIcon.svg";
import NotAllowedGreenIcon from "../../../../../assets/notAllowedGreenIcon.svg";
import { Button } from "../../../../Button";
import React, { useEffect, useState } from "react";
import DOMPurify from "dompurify";

const ChatDefaultMessageType = ({
  content,
  timestamp,
  handleClickOnMoreOptions,
  priority = "default",
  edited = false,
  onThreadClick,
  pinned,
  visibility,
  onPin,
  isUser = true,
  isThreadIconVisible,
  isPinChatIconvisible,
  isHighlighted = false,
  highlightColor = null,
}) => {
  // Function to safely render HTML content
  const renderContent = (content) => {
    if (typeof content === "string") {
      // Check if content contains HTML tags
      const hasHtmlTags = /<[^>]*>/g.test(content);

      if (hasHtmlTags) {
        // Sanitize HTML content for security
        const sanitizedContent = DOMPurify.sanitize(content, {
          ALLOWED_TAGS: [
            "p",
            "span",
            "strong",
            "em",
            "u",
            "br",
            "a",
            "ul",
            "ol",
            "li",
            "h1",
            "h2",
            "h3",
            "h4",
            "h5",
            "h6",
            "s",
            "mark",
          ],
          ALLOWED_ATTR: [
            "class",
            "data-type",
            "data-id",
            "data-label",
            "data-mention-suggestion-char",
            "href",
            "target",
            "rel",
          ],
        });

        return (
          <div
            className="message-content"
            dangerouslySetInnerHTML={{ __html: sanitizedContent }}
          />
        );
      } else {
        // Plain text content
        return <p>{content}</p>;
      }
    } else {
      // JSX content
      return content;
    }
  };

  const [showPinned, setShowPinned] = useState(pinned);

  // Create custom highlight style if highlightColor is provided
  const customHighlightStyle =
    isHighlighted && highlightColor
      ? {
          borderColor: highlightColor,
          boxShadow: `0px 0px 8px ${highlightColor}40`, // 40 is 25% opacity in hex
        }
      : {};

  const handlePin = async (isPinned) => {
    try {
      const pinnedResponse = await onPin(isPinned);

      setShowPinned(pinnedResponse?.isPinned);
    } catch (error) {
      console.error("Error pinning message:", error);
    }
  };
  useEffect(() => {
    setShowPinned(pinned);
  }, [pinned]);

  const priorityContent = {
    normal: (
      <span className="priority-label">
        <img src={CheckBlueIcon} alt="checkBlueIcon" /> Normal Priority
      </span>
    ),
    high: (
      <span className="priority-label">
        <img src={WarningRedIcon} alt="warningRedIcon" /> High Priority
      </span>
    ),
    medium: (
      <span className="priority-label">
        <img src={ThumbsUpYellowIcon} alt="thumbsUpYellowIcon" /> Medium
        Priority
      </span>
    ),
    low: (
      <span className="priority-label">
        <img src={NotAllowedGreenIcon} alt="notAllowedGreenIcon" /> Low Priority
      </span>
    ),
  };
  // pinned msg
  const pinnedIconSrc = showPinned ? PinnedIcon : UnpinIcon;
  return (
    <div
      className={`message-text ${priority} ${
        isHighlighted ? "highlighted-message-content" : ""
      }`}
      style={customHighlightStyle}
    >
      <section className="priority-container">
        {priorityContent[priority]}
      </section>
      {renderContent(content)}
      <div className={`message-header ${!isUser ? "flex-end" : ""}`}>
        {isUser ? (
          <div
            className={`message-action-container ${
              visibility ? "visibility-enabled" : ""
            }`}
          >
            <Button
              className="btn_border_default participants-button"
              icon={<ThreeDotIcon />}
              iconPlacement="left"
              size="small"
              type="default"
              variant="tertiary"
              onClick={handleClickOnMoreOptions}
            />

            {isThreadIconVisible && (
              <Button
                className="btn_border_default participants-button"
                icon={<TreadChatIcon />}
                iconPlacement="left"
                size="large"
                type="default"
                variant="tertiary"
                onClick={onThreadClick}
              />
            )}
          </div>
        ) : null}
        <div className="message-action-info-container">
          <div style={{ display: !isPinChatIconvisible ? "none" : "inline" }}>
            {showPinned && (
              <Button
                icon={<img src={pinnedIconSrc} />}
                iconPlacement="left"
                size="small"
                type="default"
                variant="tertiary"
                onClick={() => {
                  handlePin(!showPinned);
                }}
                className="pin-button"
              />
            )}
            {!showPinned && (
              <Button
                icon={<img src={PinnedIcon} />}
                iconPlacement="left"
                size="small"
                type="default"
                variant="tertiary"
                onClick={() => {
                  handlePin(!showPinned);
                }}
                className="pin-button-hover"
              />
            )}
          </div>
          <span className="message-timestamp">
            {timestamp}
            {edited && <span className="edited-label"> (edited)</span>}
          </span>
        </div>
      </div>
    </div>
  );
};

export default ChatDefaultMessageType;
