import { useEffect, useRef } from "react";
import { Box, Center, Loader, ScrollArea, Stack, Text } from "@mantine/core";
import EventBubble from "./EventBubble";
import type { MatrixEvent } from "../types";

export interface TimelineProps {
  events: MatrixEvent[];
  loading: boolean;
  error: string | null;
  selfUserID: string;
}

export default function Timeline({ events, loading, error, selfUserID }: TimelineProps) {
  const viewport = useRef<HTMLDivElement | null>(null);

  // Auto-scroll to bottom when new events arrive.
  useEffect(() => {
    if (!viewport.current) return;
    viewport.current.scrollTo({
      top: viewport.current.scrollHeight,
      behavior: "smooth",
    });
  }, [events.length]);

  if (loading && events.length === 0) {
    return (
      <Center h="100%">
        <Loader size="sm" />
      </Center>
    );
  }

  if (error) {
    return (
      <Center h="100%">
        <Text c="red" size="sm">
          {error}
        </Text>
      </Center>
    );
  }

  if (!events.length) {
    return (
      <Center h="100%">
        <Text size="sm" c="dimmed">
          No messages yet
        </Text>
      </Center>
    );
  }

  return (
    <ScrollArea h="100%" viewportRef={viewport} offsetScrollbars>
      <Box p="md">
        <Stack gap="sm">
          {events.map((ev) => (
            <EventBubble key={ev.event_id} event={ev} isSelf={ev.sender === selfUserID} />
          ))}
        </Stack>
      </Box>
    </ScrollArea>
  );
}
