import { type FC } from "react";
import { Paperclip2 } from "iconsax-react";
import { clx } from "@/helpers/utils";
import { t } from "@/locale";
import type { TicketThreadItemType } from "./types/TicketTypes";
import { formatDate } from "./detailUtils";
import { getPresignedUrl } from "@/pages/uploader/service/UploaderService";

export type MessageBubbleProps = { item: TicketThreadItemType };

const MessageBubble: FC<MessageBubbleProps> = ({ item }) => {
    const isUser = item.isFromUser;

    const handleOpenLink = async (key: string) => {
        const url = await getPresignedUrl(key);
        window.open(url, "_blank", "noopener,noreferrer");
    };

    return (
        <div
            className={clx(
                "mt-6 xl:text-sm text-xs p-6 rounded-3xl xl:max-w-[70%] max-w-[90%]",
                isUser
                    ? "bg-[#F6F7FA] rounded-tr-none"
                    : "bg-[#EBEDF5] rounded-tl-none"
            )}
        >
            <div className="flex gap-1 mb-4">
                <span className="font-bold">
                    {isUser ? t("ticket.customer") : t("ticket.expert")}
                </span>
            </div>
            <div className="leading-7">{item.content}</div>
            <div className="flex dltr end mt-6 text-xs text-description">
                {formatDate(item.createdAt)}
            </div>
            {item.attachments && item.attachments.length > 0 && (
                <div className="flex gap-2 flex-wrap text-sm mt-2">
                    {item.attachments.map((att, index) => (
                        <button
                            key={att.id}
                            type="button"
                            onClick={() => handleOpenLink(att.attachmentUrl)}
                            className="text-[#0047FF] flex gap-1 items-center"
                        >
                            <Paperclip2 size={20} color="#0047FF" />
                            {t("attach")} {index + 1}
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
};

export default MessageBubble;
