import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { Col, ListGroup, ListGroupItemHeading, Row } from "reactstrap";
import InfiniteScroll from "react-infinite-scroll-component";

import { WantViewLoading } from "src/Loading";
import EssayTitleView from "src/forum/EssayTitleView";
import WantInput from "src/want/WantInput";
import CommentTitleView from "src/forum/CommentTitleView";
import { GetWantAPIComment, GetWantAPIEssay } from "src/wwwAPI";
import useGetWant from "./useGetWant";

const WantView = () => {
  const { t } = useTranslation();

  type WantViewParams = {
    wantVariety: "essay" | "comment";
    wantInput: string;
  };
  const { wantVariety, wantInput } =
    useParams<WantViewParams>() as WantViewParams;

  const {
    fetchNextPage,
    hasNextPage,
    data: { pages },
    isFetched: isWantLoaded,
  } = useGetWant(wantVariety, wantInput);

  return (
    <>
      <WantInput />
      <hr />
      {isWantLoaded ? (
        <Row className="g-0">
          <Col className="m-1">
            <ListGroup>
              <ListGroupItemHeading>{t("wantView")}</ListGroupItemHeading>
              <InfiniteScroll
                dataLength={pages.length}
                next={() => fetchNextPage()}
                hasMore={hasNextPage}
                loader={null}
              >
                {wantVariety === "essay" &&
                  (pages as GetWantAPIEssay[]).flatMap((wantedEssayTitle) => {
                    return (
                      <EssayTitleView
                        key={wantedEssayTitle.essayID}
                        forumID={wantedEssayTitle.forumID}
                        forumTitle={wantedEssayTitle.forumTitle}
                        essay={wantedEssayTitle}
                      />
                    );
                  })}
                {wantVariety === "comment" &&
                  (pages as GetWantAPIComment[]).flatMap(
                    (wantedCommentTitle) => {
                      return (
                        <CommentTitleView
                          key={wantedCommentTitle.essayID}
                          forumID={wantedCommentTitle.forumID}
                          essayID={wantedCommentTitle.essayID}
                          comment={wantedCommentTitle}
                        />
                      );
                    },
                  )}
              </InfiniteScroll>
            </ListGroup>
          </Col>
        </Row>
      ) : (
        <WantViewLoading />
      )}
    </>
  );
};

export default WantView;
