import { Avatar, Group, Paper, Stack, Text } from "@mantine/core";
import { IconLockExclamation } from "@tabler/icons-react";
import type { MatrixEvent } from "../types";

function senderInitials(sender: string): string {
  return sender.replace(/^@/, "").charAt(0).toUpperCase() || "?";
}

function senderShort(sender: string): string {
  // "@local:server" -> "@local"
  return sender.split(":")[0];
}

function fmtTime(ts: number): string {
  if (!ts) return "";
  const d = new Date(ts);
  return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}

export interface EventBubbleProps {
  event: MatrixEvent;
  isSelf: boolean;
}

export default function EventBubble({ event, isSelf }: EventBubbleProps) {
  const isEncrypted = event.encrypted_raw;
  return (
    <Group
      align="flex-start"
      gap="xs"
      wrap="nowrap"
      justify={isSelf ? "flex-end" : "flex-start"}
    >
      {!isSelf && (
        <Avatar size={28} radius="xl" color="violet">
          {senderInitials(event.sender)}
        </Avatar>
      )}
      <Stack gap={2} maw="70%" align={isSelf ? "flex-end" : "flex-start"}>
        <Group gap={6}>
          <Text fz="xs" c="dimmed" fw={500}>
            {senderShort(event.sender)}
          </Text>
          <Text fz="xs" c="dimmed">
            {fmtTime(event.ts)}
          </Text>
        </Group>
        <Paper
          p="xs"
          radius="md"
          bg={isSelf ? "violet.9" : "dark.6"}
          c={isSelf ? "white" : "gray.0"}
          style={{ wordBreak: "break-word" }}
        >
          {isEncrypted ? (
            <Group gap={6} c="dimmed">
              <IconLockExclamation size={14} />
              <Text fz="sm" fs="italic">
                Encrypted message (no session)
              </Text>
            </Group>
          ) : (
            <Text fz="sm" style={{ whiteSpace: "pre-wrap" }}>
              {event.body || (
                <Text component="span" c="dimmed" fs="italic">
                  (no body)
                </Text>
              )}
            </Text>
          )}
        </Paper>
      </Stack>
      {isSelf && (
        <Avatar size={28} radius="xl" color="violet">
          {senderInitials(event.sender)}
        </Avatar>
      )}
    </Group>
  );
}
