import Icon from "@ant-design/icons";
import { Tooltip } from "antd";
import i18n from "i18next";
import dayjs from "../../utils/day";
import { MdClose, MdDone, MdDoneAll } from "react-icons/md";
import { DateTimeFormatter } from "../../utils/DateFormatter";

export const renderMessage = (messages, index) => {
  const message = messages[index];
  const isSystem = message.is_system;

  // Determine message class
  const messageClass = isSystem ? "system messages" : message.isoutbound ? "mine messages" : "yours messages";

  // Tooltip content based on message type
  const tooltipTitle = isSystem ? (
    i18n.t("consent.text_body")
  ) : (
    <DateTimeFormatter>{message.created_at}</DateTimeFormatter>
  );

  return (
    <div key={index} className={messageClass}>
      <div className="message msgmargin">
        <Tooltip title={tooltipTitle}>
          <div>
            {isSystem && <span className="system-label">System</span>}
            {/* Render images if available */}
            {message.image && message.image_path?.length > 0 && (
              <div className="message-images">
                {message.image_path.map((url, idx) => (
                  <div key={idx} style={{ display: "flex", justifyContent: "center" }}>
                    <a href={url} target="_blank" rel="noopener noreferrer">
                      <img alt="Received" className="message-img" src={url} />
                    </a>
                  </div>
                ))}
              </div>
            )}
            {/* Render text if available */}
            {message.text && <div className="message-text">{message.text}</div>}
            {/* Render date for system messages */}
            {isSystem && (
              <div className="system-date">
                <DateTimeFormatter>{message.created_at}</DateTimeFormatter>
              </div>
            )}
          </div>
        </Tooltip>

        {/* Message status icons for non-system messages */}
        {!isSystem &&
          message.status &&
          (message.status === "sent" || message.status === "delivered" || message.status === "failed") && (
            <div className="message-status">
              <Icon
                component={message.status === "sent" ? MdDone : message.status === "delivered" ? MdDoneAll : MdClose}
                className="message-icon"
                style={message.status === "failed" ? { color: "#ff0000" } : undefined}
              />
            </div>
          )}
      </div>
      {/* Outbound message metadata for non-system messages */}
      {!isSystem && message.isoutbound && (
        <div style={{ fontSize: 10 }}>
          {i18n.t("messaging.labels.sentby", {
            by: message.userid,
            time: dayjs(message.created_at).format("MM/DD/YYYY @ hh:mm a")
          })}
        </div>
      )}
    </div>
  );
};
