import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { getLanguage } from "taehui-ts/language";

import { wwwAXIOS } from "src/Www";
import { LatestEssaysViewLoading } from "src/Loading";
import EssayTitleView from "src/forum/EssayTitleView";
import { ListGroup, ListGroupItemHeading } from "reactstrap";
import { GetLatestEssayAPI } from "src/wwwAPI";

const LatestEssaysView = () => {
  const [isLoading, setLoading] = useState(true);
  const [latestEssays, setLatestEssays] = useState<GetLatestEssayAPI>([]);

  const { t } = useTranslation();

  useEffect(() => {
    (async () => {
      const { status, data } = await wwwAXIOS.get<GetLatestEssayAPI>(
        "/essay/latest",
        {
          params: { language: getLanguage() },
        },
      );

      if (status === 200) {
        setLatestEssays(data);
        setLoading(false);
      }
    })();
  }, []);

  return (
    <>
      <ListGroup>
        <ListGroupItemHeading>{t("latestEssaysView")}</ListGroupItemHeading>
        {isLoading ? (
          <LatestEssaysViewLoading />
        ) : (
          latestEssays.map((latestEssay) => {
            return (
              <EssayTitleView
                key={latestEssay.essayID}
                forumID={latestEssay.forumID}
                forumTitle={latestEssay.forumTitle}
                essay={latestEssay}
              />
            );
          })
        )}
      </ListGroup>
    </>
  );
};

export default LatestEssaysView;
