"use client";

import WantInput from "@/app/[language]/want/components/WantInput";
import useGetWant from "@/app/[language]/want/query/useGetWant";
import CommentTitleView from "@/components/CommentTitleView";
import EssayTitleView from "@/components/EssayTitleView";
import { useWantStore } from "@/state/Stores";
import { GetWantAPIComment, GetWantAPIEssay } from "@/type/wwwAPI";
import { useParams } from "next/navigation";
import { useEffect, useMemo } from "react";
import ListGroup from "react-bootstrap/ListGroup";
import ListGroupItem from "react-bootstrap/ListGroupItem";
import Stack from "react-bootstrap/Stack";
import InfiniteScroll from "react-infinite-scroll-component";

export default function Page() {
  const { setInput } = useWantStore();

  const { wantVariety } = useParams<{
    wantVariety: "essay" | "comment";
  }>();
  let { wantInput: [wantInput] = [""] } = useParams<{
    wantInput: string[];
  }>();
  wantInput = useMemo(() => decodeURIComponent(wantInput), [wantInput]);

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

  useEffect(() => {
    setInput(wantInput);
  }, [setInput, wantInput]);

  return (
    <Stack gap={2}>
      <WantInput />
      {isWantLoaded && (pages as unknown[]).length > 0 && (
        <>
          <hr />
          <ListGroup>
            <InfiniteScroll
              dataLength={pages.length}
              next={() => fetchNextPage()}
              hasMore={hasNextPage}
              loader={null}
            >
              {wantVariety === "essay" &&
                (pages as GetWantAPIEssay[]).flatMap((wantedEssayTitle) => (
                  <ListGroupItem key={wantedEssayTitle.essayID}>
                    <EssayTitleView
                      forumID={wantedEssayTitle.forumID}
                      forumTitle={wantedEssayTitle.forumTitle}
                      essay={wantedEssayTitle}
                    />
                  </ListGroupItem>
                ))}
              {wantVariety === "comment" &&
                (pages as GetWantAPIComment[]).flatMap((wantedCommentTitle) => (
                  <ListGroupItem key={wantedCommentTitle.essayID}>
                    <CommentTitleView
                      forumID={wantedCommentTitle.forumID}
                      essayID={wantedCommentTitle.essayID}
                      comment={wantedCommentTitle}
                    />
                  </ListGroupItem>
                ))}
            </InfiniteScroll>
          </ListGroup>
        </>
      )}
    </Stack>
  );
}
