import React from "react";
import { Avatar } from "../../../../Avatar";
import { ChatInput } from "../ChatInput/ChatInput";
import { ChatAvatar } from "../AvatarGroup/AvatarGroup";
import BlockIcon from "@mui/icons-material/Block";
import DOMPurify from "dompurify";
import "./PinedChat.styles.scss";

// Function to safely render HTML content
const renderContent = (content) => {
  if (!content) return null;

  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-html"
          dangerouslySetInnerHTML={{ __html: sanitizedContent }}
        />
      );
    } else {
      // Plain text content
      return <span>{content}</span>;
    }
  } else {
    // JSX content
    return content;
  }
};

// 🔹 Reusable Message Component
const MessageItem = ({ type, msg, onMessageClick }) => {
  const isPinned = type === "pinned";
  // Check if message is deleted (check both type and deleted property)
  const isDeleted = msg?.type === "deleted" || msg?.deleted === true;

  const handleClick = () => {
    if (onMessageClick && msg?.id) {
      onMessageClick(msg.id);
    }
  };

  // If message is deleted, render deleted message component
  if (isDeleted) {
    return (
      <div
        className={isPinned ? "pinned-message" : "thread-message"}
        onClick={handleClick}
        style={{ cursor: "pointer" }}
      >
        {/* Avatar */}
        {isPinned ? (
          <Avatar
            label={msg?.userInitials}
            size="small"
            src={msg?.src || "static/media/src/assets/avatar_sample.jpeg"}
            type="withoutPicture"
          />
        ) : (
          <ChatAvatar
            src={msg?.src || "static/media/src/assets/avatar_sample.jpeg"}
            name={msg?.userInitials}
            size="sm"
          />
        )}

        {/* Message Info */}
        <div className={isPinned ? "pinned-info" : "thread-info"}>
          {/* Meta Info */}
          {isPinned && (
            <div className="pinned-meta">
              <span className="user-title">{msg.senderName}</span>
              {type === "pinned" && (
                <span className="pinned-time">{msg.timestamp}</span>
              )}
            </div>
          )}

          {/* Deleted Message Component */}
          <div className={isPinned ? "pinned-text" : "thread-text"}>
            <div className="deleted-message-content">
              <BlockIcon className="delete-icon" />
              <span className="deleted-text">
                Message deleted by its author
              </span>
            </div>
          </div>
          {type === "thread" && (
            <span className="thread-time">{msg.timestamp}</span>
          )}
        </div>
      </div>
    );
  }

  return (
    <div
      className={isPinned ? "pinned-message" : "thread-message"}
      onClick={handleClick}
      style={{ cursor: "pointer" }}
    >
      {/* Avatar */}
      {isPinned ? (
        <Avatar
          label={msg?.userInitials}
          size="small"
          src={msg?.src || "static/media/src/assets/avatar_sample.jpeg"}
          type="withoutPicture"
        />
      ) : (
        <ChatAvatar
          src={msg?.src || "static/media/src/assets/avatar_sample.jpeg"}
          name={msg?.userInitials}
          size="sm"
        />
      )}

      {/* Message Info */}
      <div className={isPinned ? "pinned-info" : "thread-info"}>
        {/* Meta Info */}
        {isPinned && (
          <div className="pinned-meta">
            <span className="user-title">{msg.senderName}</span>
            {type === "pinned" && (
              <span className="pinned-time">
                {msg.timestamp}
                {/* {msg.edited && <span className="edited-label"> (edited)</span>} */}
              </span>
            )}
          </div>
        )}

        {/* Quote (only for thread) */}
        {!isPinned && msg.quote && (
          <div className="thread-quote-container">
            <p className="thread_title">{msg.senderName}</p>
            <blockquote className="thread-quote">
              {renderContent(msg.quote)}
            </blockquote>
          </div>
        )}

        {/* Main Text */}
        <div className={isPinned ? "pinned-text" : "thread-text"}>
          {renderContent(msg.content)}
        </div>
        {type === "thread" && (
          <span className="thread-time">
            {msg.timestamp}
            {msg.edited && <span className="edited-label"> (edited)</span>}
          </span>
        )}
      </div>
    </div>
  );
};

// 🔹 Main Panel Component
export const PinnedPanel = ({
  type = "pinned", // "pinned" or "thread"
  messages = [],
  onClose,
  onMessageClick, // Handler when a message is clicked
}) => {
  const isPinned = type === "pinned";

  return (
    <div className="pinned-panel">
      {/* Header */}
      <div className="pinned-panel-header">
        <h1 className="header-title">{isPinned ? "Pinned" : "Thread"}</h1>
        <button className="close-btn" onClick={onClose}>
          {isPinned ? "Close" : "Close thread"}
        </button>
      </div>

      {/* Content */}
      <div className="pinned-panel-content">
        {isPinned && <h4 className="pinned-title">Pinned message</h4>}

        {messages?.map((msg, idx) => (
          <MessageItem
            key={msg.id}
            type={type}
            msg={msg}
            onMessageClick={onMessageClick}
          />
        ))}
      </div>
      {type === "thread" && (
        <ChatInput
          placeholder={"Thread Msg"}
          value={""}
          onChange={() => {}}
          onSend={() => {}}
          onAttach={""}
          onImageUpload={""}
          onEmojiClick={() => {}}
          showFormatting={true}
          showQuickAction={true}
          quickActionLabel={"Quick Action"}
          maxLength={500}
        />
      )}
    </div>
  );
};
