import React, { useCallback } from 'react';
import { Text, color } from 'folds';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { usePowerLevels } from '../../hooks/usePowerLevels';
import { PowerLevelsContextProvider } from '../../hooks/usePowerLevels';
import { useForumBoardContext } from './ForumBoardContext';
import { ForumFilterBar } from './ForumFilterBar';
import { ForumPostList } from './ForumPostList';
import { ForumNewPostBox } from './ForumNewPostBox';
import type { ForumPublishedPost } from './types';
import * as theme from './forumTheme.css';

/** Categories, filters, and post list in the space sidebar (matrixsso-style). */
export function ForumFeedSidebar() {
  const mx = useMatrixClient();

  const {
    forumSpace,
    sections,
    threads,
    query,
    loadingSections,
    loadingThreads,
    error,
    selectedPostId,
    setQueryParam,
    setCategory,
    selectPost,
    loadMorePosts,
    hasMorePosts,
    loadingMore,
    insertThreadFromNewPost,
  } = useForumBoardContext();

  const spacePowerLevels = usePowerLevels(forumSpace);

  const getTopicRoom = useCallback(
    (roomId: string | undefined) => (roomId ? mx.getRoom(roomId) : null),
    [mx]
  );

  const handlePostPublished = useCallback(
    (published: ForumPublishedPost) => {
      insertThreadFromNewPost(published);
      selectPost(published.eventId, published.topicRoomId);
    },
    [insertThreadFromNewPost, selectPost]
  );

  return (
    <PowerLevelsContextProvider value={spacePowerLevels}>
      <div className={theme.ForumFeedSidebarRoot}>
        <section className={theme.ForumFiltersCard}>
          <ForumFilterBar
            sections={sections}
            threads={threads}
            query={query}
            onQueryChange={setQueryParam}
            onCategoryChange={setCategory}
          />
        </section>
        <section className={theme.ForumListCard}>
          {error && (
            <Text as="p" className={theme.ForumListLoading} style={{ color: color.Critical.Main }}>
              {error}
            </Text>
          )}
          <ForumNewPostBox
            sections={sections}
            postCount={threads.length}
            loading={loadingSections || loadingThreads}
            hasMore={hasMorePosts}
            defaultCategory={query.category}
            defaultTopicRoomId={query.topic}
            onPublished={handlePostPublished}
          />
          <ForumPostList
            threads={threads}
            selectedPostId={selectedPostId}
            loading={loadingSections || loadingThreads}
            getTopicRoom={getTopicRoom}
            onSelectPost={selectPost}
            hasMore={hasMorePosts}
            loadingMore={loadingMore}
            onLoadMore={loadMorePosts}
          />
        </section>
      </div>
    </PowerLevelsContextProvider>
  );
}
