import { useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import {
  Badge,
  Button,
  Col,
  ListGroup,
  ListGroupItemHeading,
  Row,
} from "reactstrap";
import { observer } from "mobx-react-lite";
import { useTranslation } from "react-i18next";
import { useIntParam, useTo } from "taehui-ts/fe-utility";

import EssayTitleView from "src/forum/EssayTitleView";
import PositionInput from "src/forum/PositionInput";
import { useAvatarStore, useForumStore } from "src/Stores";
import { ForumViewLoading } from "src/Loading";
import useGetForum from "src/forum/useGetForum";

export default observer(() => {
  const { taehuiLevel } = useAvatarStore();
  const { viewUnit, setLastPage } = useForumStore();
  const { t } = useTranslation();

  type ForumViewParams = {
    forumID: string;
  };
  const { forumID } = useParams<ForumViewParams>() as ForumViewParams;
  const { param: page } = useIntParam("page", 1);

  const to = useTo();

  const {
    data: { title, essays, essayCount, level },
    isFetched: isForumLoaded,
  } = useGetForum(forumID, page, viewUnit);

  useEffect(() => {
    if (isForumLoaded) {
      setLastPage(Math.ceil(essayCount / viewUnit));
    }
  }, [essayCount, isForumLoaded, setLastPage, viewUnit]);

  return (
    <>
      <Row className="g-0">
        <Col className="m-1">
          <ListGroup>
            <ListGroupItemHeading>
              <Badge>{title}</Badge>
            </ListGroupItemHeading>
            {isForumLoaded ? (
              essays.map((essay) => (
                <EssayTitleView
                  forumID={forumID}
                  essay={essay}
                  key={essay.essayID}
                />
              ))
            ) : (
              <ForumViewLoading />
            )}
          </ListGroup>
        </Col>
      </Row>
      <Row className="justify-content-center g-0">
        <Col className="m-1" xs="auto">
          <PositionInput />
        </Col>
      </Row>
      <Row className="g-0">
        {taehuiLevel >= level && (
          <Col className="m-1 text-end">
            <Link to={`/forum/${forumID}/w`}>
              <Button color="success">{t("postEssay")}</Button>
            </Link>
          </Col>
        )}
        <Col
          className="m-1 text-end"
          xs={taehuiLevel >= level ? "auto" : undefined}
        >
          <Button
            color="danger"
            onClick={() => {
              to("/forums");
            }}
          >
            {t("quit")}
          </Button>
        </Col>
      </Row>
    </>
  );
});
