import React, { KeyboardEventHandler } from 'react';
import { Box, Button, Scroll, Spinner, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { Room } from 'matrix-js-sdk';
import type { ForumThreadSummary } from './types';
import { formatForumTimeAgo } from './forumTime';
import { ForumPostAuthor } from './ForumPostAuthor';
import * as t from './forumTheme.css';

function categoryTopicLabel(thread: ForumThreadSummary): string {
  const section = thread.sectionTitle || '';
  const topic = thread.topicName || '';
  if (section && topic) return `${section}/${topic}`;
  if (topic) return topic;
  if (section) return `${section}/all topics`;
  return 'all categories / all topics';
}

type ForumPostListProps = {
  threads: ForumThreadSummary[];
  selectedPostId: string | null;
  loading: boolean;
  getTopicRoom: (roomId: string | undefined) => Room | null;
  onSelectPost: (eventId: string, topicRoomId?: string) => void;
  hasMore?: boolean;
  loadingMore?: boolean;
  onLoadMore?: () => void;
};

export function ForumPostList({
  threads,
  selectedPostId,
  loading,
  getTopicRoom,
  onSelectPost,
  hasMore = false,
  loadingMore = false,
  onLoadMore,
}: ForumPostListProps) {
  return (
    <>
      <Scroll
        className={t.ForumPostScroll}
        variant="Background"
        direction="Vertical"
        size="300"
        hideTrack
        visibility="Hover"
      >
        {loading && threads.length === 0 && (
          <Box alignItems="Center" gap="200" style={{ padding: '1rem' }}>
            <Spinner size="200" />
            <Text size="T300" priority="300">
              Loading posts…
            </Text>
          </Box>
        )}
        {!loading && threads.length === 0 && (
          <Text as="p" className={t.ForumListLoading} size="T300" priority="300">
            No threads match these filters.
          </Text>
        )}
        <ul className={t.ForumPostList}>
          {threads.map((thread) => {
            const isActive = thread.eventId === selectedPostId;
            const topicRoom = getTopicRoom(thread.topicRoomId);

            const handleKeyDown: KeyboardEventHandler<HTMLDivElement> = (event) => {
              if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                onSelectPost(thread.eventId, thread.topicRoomId);
              }
            };

            return (
              <li key={thread.eventId} className={t.ForumPostItem}>
                <div
                  role="button"
                  tabIndex={0}
                  className={t.ForumPostLink}
                  data-active={isActive ? 'true' : undefined}
                  data-pinned={thread.isPinned ? 'true' : undefined}
                  onClick={() => onSelectPost(thread.eventId, thread.topicRoomId)}
                  onKeyDown={handleKeyDown}
                >
                  <div className={t.ForumPostHead}>
                    <div className={t.ForumPostHeadMain}>
                      {thread.isPinned && <Icon src={Icons.Pin} size="100" filled />}
                      <span className={t.ForumPostTitle} data-role="title">
                        {thread.title}
                      </span>
                    </div>
                    {thread.totalReplies > 0 && (
                      <Box as="span" className={t.ForumReplyMeta} alignItems="Center" gap="100" aria-hidden>
                        {thread.totalReplies > 1 && (
                          <Text as="span" className={t.ForumReplyCount} size="L400">
                            {thread.totalReplies}
                          </Text>
                        )}
                        <Icon
                          src={thread.totalReplies === 1 ? Icons.Mail : Icons.MailPlus}
                          size="100"
                        />
                      </Box>
                    )}
                  </div>
                  <div className={t.ForumPostFoot}>
                    <ForumPostAuthor
                      room={topicRoom}
                      sender={thread.sender}
                      displayName={thread.senderDisplayName}
                    />
                    <div className={t.ForumPostMeta}>
                      <span className={t.ForumCategoryLabel}>{categoryTopicLabel(thread)}</span>
                      <Text as="span" size="L400" priority="300">
                        {formatForumTimeAgo(thread.lastActivityTs)}
                      </Text>
                    </div>
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      </Scroll>
      {hasMore && onLoadMore && (
        <div className={t.ForumListFooter}>
          <Button
            variant="Secondary"
            size="300"
            radii="300"
            fill="Soft"
            onClick={onLoadMore}
            disabled={loadingMore}
          >
            {loadingMore ? <Spinner size="100" /> : <Text size="B400">Load older posts</Text>}
          </Button>
        </div>
      )}
    </>
  );
}
