import { Link } from "react-router-dom";
import { Message, User, Channel } from "../types";

import "../styles/MessageComponent.css";

export default function MessageComponent({ message, user, channel, deleteMessage }: {
        message: Message;
        user: User | undefined;
        channel: Channel | undefined;
        deleteMessage: ((messageId: number) => void) | undefined;
    }) {
    
    return (
        <div key={message.id} className="message">
            <Link to={`/u/${message.username}`}>{message.username}</Link>:{" "}
            {message.content.split(" ").map((word, index) => {
                if (word.startsWith("@")) {
                    const mention = message.mentions.find((mention) => `@${mention.username}` === word);
                    if (mention) {
                        return <span><Link key={index} to={`/u/${mention.username}`}>{word}</Link> </span>;
                    }
                }
                return <span key={index}>{word} </span>;
            })}
            <p>{new Date(message.date * 1000).toLocaleString()}</p>
            <div>
                {message.content.toLocaleLowerCase().includes("gros cochon") && (
                    <img src="/pig.png" alt="Gros cochon" className="pig" />
                )}
            </div>
            {channel && deleteMessage ? (
                user?.id === message.user_id || user?.id === channel?.owner_id || user?.admin === 1) && (
                    <button onClick={() => {deleteMessage(message.id)}}>Delete</button>
                ) : (
                    <p>In <Link to={`/c/${message.channel_name}`}>{message.channel_name}</Link></p>
                )
            }
        </div>
    );
}