import React, { useCallback, useState } from 'react';
import { Box, Button, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import type { ForumPost, ForumPublishedPost, ForumSection } from './types';
import { ForumNewPostModal } from './ForumNewPostModal';
import * as t from './forumTheme.css';

function formatShowingPosts(count: number, loading: boolean, hasMore: boolean): string {
  if (loading && count === 0) {
    return 'Loading posts…';
  }
  const suffix = hasMore && count > 0 ? '+' : '';
  const noun = count === 1 ? 'post' : 'posts';
  return `Showing ${count}${suffix} ${noun}`;
}

type ForumNewPostBoxProps = {
  sections: ForumSection[];
  postCount: number;
  loading?: boolean;
  hasMore?: boolean;
  defaultCategory?: string;
  defaultTopicRoomId?: string;
  onPublished?: (published: ForumPublishedPost) => void;
};

export function ForumNewPostBox({
  sections,
  postCount,
  loading = false,
  hasMore = false,
  defaultCategory,
  defaultTopicRoomId,
  onPublished,
}: ForumNewPostBoxProps) {
  const mx = useMatrixClient();
  const [modalOpen, setModalOpen] = useState(false);
  const userId = mx.getUserId();

  const handleOpen = useCallback(() => {
    setModalOpen(true);
  }, []);

  return (
    <>
      <Box className={t.ForumNewPostBox}>
        <Text as="p" className={t.ForumPostCountMeta} size="T200" priority="300">
          {formatShowingPosts(postCount, loading, hasMore)}
        </Text>
        {userId ? (
          <Button variant="Secondary" size="300" radii="300" onClick={handleOpen}>
            <Icon src={Icons.Plus} size="100" />
            <Text size="B400">New post</Text>
          </Button>
        ) : null}
      </Box>
      {modalOpen && userId && (
        <ForumNewPostModal
          sections={sections}
          initialCategory={defaultCategory}
          initialTopicRoomId={defaultTopicRoomId}
          onClose={() => setModalOpen(false)}
          onPublished={onPublished}
        />
      )}
    </>
  );
}
