import { X } from "lucide-react";
import { Button, DynText } from "../../ui/primitives";
import type { MessageRecord } from "../../store";
import { t } from "../../i18n";
import { formatRelative } from "../../utils/format";
import s from "./MessageList.module.css";

export interface MessageListProps
{
    messages: MessageRecord[];
    onDismiss: (id: string) => void;
    onClearAll: () => void;
}

export function MessageList(props: MessageListProps)
{
    const { messages, onDismiss, onClearAll } = props;
    if (messages.length === 0) { return null; }

    return (
        <section className={s.section}>
            <div className={s.head}>
                <div>
                    <span className={s.title}>{t("home.message.title")}</span>
                    <span className={s.count}>
                        <DynText>{t("home.message.countSuffix", { count: messages.length })}</DynText>
                    </span>
                </div>
                <Button variant="ghost" size="sm" onClick={onClearAll}>
                    {t("home.message.clearAll")}
                </Button>
            </div>

            <div className={s.list}>
                {messages.map((m) => (
                    <MessageRow key={m.id} m={m} onDismiss={() => onDismiss(m.id)} />
                ))}
            </div>
        </section>
    );
}

function MessageRow(props: { m: MessageRecord; onDismiss: () => void })
{
    const { m, onDismiss } = props;
    const arrow = m.direction === "outgoing" ? "→" : "←";
    const cls = [ s.row, m.direction === "incoming" ? s.rowIncoming : "" ].join(" ");

    return (
        <div className={cls}>
            <div className={s.body}>
                <div className={s.meta}>{arrow} {m.peerName} · <DynText>{formatRelative(m.sentAt)}</DynText></div>
                <div className={`${s.text} justify`} data-jz-level="paragraph">{m.text}</div>
            </div>
            <button
                type="button"
                className={s.dismiss}
                aria-label={t("common.dismiss")}
                onClick={onDismiss}
            >
                <X size={14} />
            </button>
        </div>
    );
}
