import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Text, color, Scroll } from 'folds';
import { Icon, Icons } from '../../components/icons';
import classNames from 'classnames';
import { useSetAtom } from 'jotai';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { usePowerLevels } from '../../hooks/usePowerLevels';
import { PowerLevelsContextProvider } from '../../hooks/usePowerLevels';
import { Page, PageContent } from '../../components/page';
import { ContainerColor } from '../../styles/ContainerColor.css';
import { LobbyHeader } from '../lobby/LobbyHeader';
import { activeThreadIdAtomFamily } from '../../state/activeThread';
import { useForumBoardContext } from './ForumBoardContext';
import { ForumFilterBar } from './ForumFilterBar';
import { ForumPostList } from './ForumPostList';
import { ForumNewPostBox } from './ForumNewPostBox';
import { ForumThreadDetail } from './ForumThreadDetail';
import type { ForumPost, ForumPublishedPost } from './types';
import * as theme from './forumTheme.css';

/** matrixsso-style feed in the Cinny main pane (Paarrot theme + folds icons). */
export function ForumSpaceShell() {
  const mx = useMatrixClient();
  const [optimisticPost, setOptimisticPost] = useState<ForumPost | null>(null);

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

  const spacePowerLevels = usePowerLevels(forumSpace);
  const activeTopicRoom = activeTopicRoomId ? mx.getRoom(activeTopicRoomId) : null;
  const topicSelected = Boolean(query.topic);

  const setActiveThreadId = useSetAtom(
    activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId)
  );

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

  useEffect(() => {
    if (optimisticPost && optimisticPost.eventId !== selectedPostId) {
      setOptimisticPost(null);
    }
  }, [optimisticPost, selectedPostId]);

  const selectedThread = useMemo(
    () => threads.find((t) => t.eventId === selectedPostId),
    [threads, selectedPostId]
  );

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

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

  const handleReplySent = useCallback(
    (_reply: ForumPost) => {
      if (selectedPostId) {
        recordThreadReply(selectedPostId);
      }
    },
    [recordThreadReply, selectedPostId]
  );

  const showThread = Boolean(selectedPostId && activeTopicRoom);

  const threadInitialPost =
    optimisticPost?.eventId === selectedPostId ? optimisticPost : null;
  const detailDropRef = useRef<HTMLDivElement>(null);

  return (
    <PowerLevelsContextProvider value={spacePowerLevels}>
      <Page className={classNames(ContainerColor({ variant: 'Background' }), theme.ForumAppRoot)}>
        <PageContent className={theme.ForumPageContent}>
          <main id="topicLiveApp" className={theme.ForumTopicLiveApp}>
            <section className={theme.ForumBlenderLayout}>
              <div className={theme.ForumLeftColumn}>
                <div className={theme.ForumLeftHeader}>
                  <LobbyHeader showSpaceToolbar powerLevels={spacePowerLevels} />
                </div>
                <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>

              <aside className={theme.ForumDetailPane}>
                {showThread && activeTopicRoom ? (
                  <div ref={detailDropRef} className={theme.ForumTopicPostDetailThreadLayout}>
                    <ForumThreadDetail
                      roomId={activeTopicRoom.roomId}
                      rootEventId={selectedPostId!}
                      titleHint={selectedThread?.title}
                      initialPost={threadInitialPost}
                      fileDropContainerRef={detailDropRef}
                      onReplySent={handleReplySent}
                    />
                  </div>
                ) : (
                  <Scroll
                    id="topicPostDetail"
                    className={theme.ForumTopicPostDetailScroll}
                    variant="Surface"
                    direction="Vertical"
                    size="300"
                    hideTrack
                    visibility="Hover"
                  >
                    <div className={theme.ForumTopicPostDetailInner}>
                      <Box
                        className={theme.ForumEmptyDetail}
                        direction="Column"
                        alignItems="Center"
                        justifyContent="Center"
                        gap="300"
                      >
                        <Icon src={Icons.Thread} size="600" />
                        <Text size="T300" priority="300">
                          {topicSelected
                            ? 'Select a post to read the thread'
                            : 'Pick a category and topic, then choose a post'}
                        </Text>
                      </Box>
                    </div>
                  </Scroll>
                )}
              </aside>
            </section>
          </main>
        </PageContent>
      </Page>
    </PowerLevelsContextProvider>
  );
}
