import { Avatar, Group, NavLink, ScrollArea, Stack, Text } from "@mantine/core";
import { IconLock, IconHash, IconUser } from "@tabler/icons-react";
import type { RoomSummary } from "../types";

function relativeTime(ts: number): string {
  if (!ts) return "";
  const diff = Date.now() - ts;
  const sec = Math.floor(diff / 1000);
  if (sec < 60) return `${sec}s`;
  const min = Math.floor(sec / 60);
  if (min < 60) return `${min}m`;
  const hr = Math.floor(min / 60);
  if (hr < 24) return `${hr}h`;
  const day = Math.floor(hr / 24);
  if (day < 30) return `${day}d`;
  return new Date(ts).toLocaleDateString();
}

function initial(room: RoomSummary): string {
  const base = room.name || room.canonical_alias || room.room_id;
  return (base.replace(/^[#@!]/, "").charAt(0) || "?").toUpperCase();
}

export interface RoomListProps {
  rooms: RoomSummary[];
  activeRoomID: string | null;
  onSelect: (roomID: string) => void;
}

export default function RoomList({ rooms, activeRoomID, onSelect }: RoomListProps) {
  if (!rooms.length) {
    return (
      <Stack p="md">
        <Text size="sm" c="dimmed">
          No rooms yet. Sync in progress...
        </Text>
      </Stack>
    );
  }

  return (
    <ScrollArea h="calc(100vh - 56px)" type="hover" offsetScrollbars>
      <Stack gap={0} p={4}>
        {rooms.map((room) => {
          const active = room.room_id === activeRoomID;
          const TypeIcon = room.is_direct ? IconUser : IconHash;
          return (
            <NavLink
              key={room.room_id}
              active={active}
              variant="filled"
              color="violet"
              onClick={() => onSelect(room.room_id)}
              leftSection={
                <Avatar size={32} radius="xl" color={active ? "violet" : "gray"}>
                  {initial(room)}
                </Avatar>
              }
              label={
                <Group gap={6} wrap="nowrap" justify="space-between">
                  <Group gap={4} wrap="nowrap" style={{ minWidth: 0 }}>
                    <TypeIcon size={12} style={{ flexShrink: 0, opacity: 0.6 }} />
                    <Text truncate fz="sm" fw={active ? 600 : 500}>
                      {room.name || room.canonical_alias || room.room_id}
                    </Text>
                  </Group>
                  {room.is_encrypted && (
                    <IconLock size={12} style={{ flexShrink: 0, opacity: 0.7 }} />
                  )}
                </Group>
              }
              description={
                <Group gap={6} justify="space-between" wrap="nowrap">
                  <Text fz="xs" c="dimmed" truncate>
                    {room.member_count} member{room.member_count === 1 ? "" : "s"}
                  </Text>
                  <Text fz="xs" c="dimmed">
                    {relativeTime(room.last_event_ts)}
                  </Text>
                </Group>
              }
            />
          );
        })}
      </Stack>
    </ScrollArea>
  );
}
