import React, { useCallback, useEffect, useRef } from 'react';
import { Box, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { Room } from 'matrix-js-sdk';
import { useSetAtom } from 'jotai';
import { Page, PageContent } from '../../components/page';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { PowerLevelsContextProvider, usePowerLevels } from '../../hooks/usePowerLevels';
import { ThreadView } from '../room/ThreadView';
import { RoomInput } from '../room/RoomInput';
import { useEditor } from '../../components/editor';
import { activeThreadIdAtomFamily } from '../../state/activeThread';
import { useForumBoard, type ForumBoardScope } from './useForumBoard';
import { ForumFilterBar } from './ForumFilterBar';
import { ForumPostList } from './ForumPostList';
import { ForumNewPostBox } from './ForumNewPostBox';
import type { ForumPublishedPost } from './types';
import * as css from './ForumBoardView.css';

type ForumBoardViewProps = {
  forumSpace: Room;
  scope: ForumBoardScope;
};

export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) {
  const mx = useMatrixClient();
  const editor = useEditor();
  const detailScrollRef = useRef<HTMLDivElement>(null);
  const {
    sections,
    threads,
    query,
    loadingSections,
    loadingThreads,
    error,
    selectedPostId,
    activeTopicRoomId,
    setQueryParam,
    setCategory,
    selectPost,
    loadMorePosts,
    hasMorePosts,
    loadingMore,
    insertThreadFromNewPost,
    recordThreadReply,
  } = useForumBoard(scope, forumSpace);

  const activeTopicRoom = activeTopicRoomId ? mx.getRoom(activeTopicRoomId) : null;
  const topicPowerLevels = usePowerLevels(activeTopicRoom ?? forumSpace);
  const setActiveThreadId = useSetAtom(
    activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId)
  );

  const topicSelected = Boolean(query.topic || scope.topicRoomId);

  useEffect(() => {
    if (selectedPostId && activeTopicRoomId) {
      setActiveThreadId(selectedPostId);
      return () => setActiveThreadId(undefined);
    }
    setActiveThreadId(undefined);
    return undefined;
  }, [selectedPostId, activeTopicRoomId, setActiveThreadId]);

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

  const handlePostPublished = useCallback(
    (published: ForumPublishedPost) => {
      insertThreadFromNewPost(published);
      selectPost(published.eventId, published.topicRoomId);
      detailScrollRef.current?.scrollIntoView({ behavior: 'smooth' });
    },
    [insertThreadFromNewPost, selectPost]
  );

  const showComposer = Boolean(activeTopicRoom && (!selectedPostId || topicSelected));

  return (
    <Page>
      <PageContent>
        <Box className={css.ForumBoardRoot}>
          {error && (
            <Box style={{ padding: '0.5rem 1rem' }}>
              <Text style={{ color: 'var(--fc-critical, #f38ba8)' }}>{error}</Text>
            </Box>
          )}

          <Box className={css.ForumBoardGrid}>
            <Box className={css.ForumFiltersCard}>
              <ForumFilterBar
                sections={sections}
                threads={threads}
                query={query}
                hideCategoryTopic={Boolean(scope.topicRoomId)}
                onQueryChange={setQueryParam}
                onCategoryChange={setCategory}
              />
            </Box>

            <Box className={css.ForumListCard}>
              <ForumNewPostBox
                sections={sections}
                postCount={threads.length}
                loading={loadingSections || loadingThreads}
                hasMore={hasMorePosts}
                defaultCategory={query.category}
                defaultTopicRoomId={activeTopicRoomId ?? query.topic}
                onPublished={handlePostPublished}
              />
              <ForumPostList
                threads={threads}
                selectedPostId={selectedPostId}
                loading={loadingSections || loadingThreads}
                getTopicRoom={getTopicRoom}
                onSelectPost={selectPost}
                hasMore={hasMorePosts}
                loadingMore={loadingMore}
                onLoadMore={loadMorePosts}
              />
            </Box>

            <Box className={css.ForumDetailPanel}>
              <Box ref={detailScrollRef} className={css.ForumDetailScroll}>
                {selectedPostId && activeTopicRoom ? (
                  <PowerLevelsContextProvider value={topicPowerLevels}>
                    <ThreadView room={activeTopicRoom} threadRootId={selectedPostId} />
                  </PowerLevelsContextProvider>
                ) : (
                  <Box grow="Yes" alignItems="Center" justifyContent="Center" direction="Column" gap="200">
                    <Icon src={Icons.Thread} size="600" />
                    <Text priority="300">
                      {topicSelected
                        ? 'Select a post or create a new one'
                        : 'Select a topic to browse posts'}
                    </Text>
                  </Box>
                )}

                {showComposer && activeTopicRoom && (
                  <Box
                    shrink="No"
                    direction="Column"
                    style={{ padding: '0.75rem', borderTop: '1px solid var(--fc-surface-container)' }}
                  >
                    <PowerLevelsContextProvider value={topicPowerLevels}>
                      <RoomInput
                        room={activeTopicRoom}
                        editor={editor}
                        roomId={activeTopicRoom.roomId}
                        fileDropContainerRef={detailScrollRef}
                      />
                    </PowerLevelsContextProvider>
                  </Box>
                )}
              </Box>
            </Box>
          </Box>
        </Box>
      </PageContent>
    </Page>
  );
}
