"use client";

import PositionInput from "@/app/[language]/forum/components/PositionInput";
import useGetForum from "@/app/[language]/forum/query/useGetForum";
import EssayTitleView from "@/components/EssayTitleView";
import { useForumStore, useTaehuiStore } from "@/state/Stores";
import { observer } from "mobx-react-lite";
import { useTranslations } from "next-intl";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { PencilFill } from "react-bootstrap-icons";
import Button from "react-bootstrap/Button";
import Col from "react-bootstrap/Col";
import ListGroup from "react-bootstrap/ListGroup";
import ListGroupItem from "react-bootstrap/ListGroupItem";
import Row from "react-bootstrap/Row";
import Stack from "react-bootstrap/Stack";

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

  const { forumID } = useParams<{
    forumID: string;
  }>();
  const searchParams = useSearchParams();

  const { push } = useRouter();

  const {
    data: { title, essays, essayCount, level },
    isFetched: isForumLoaded,
  } = useGetForum(forumID, Number.parseInt(searchParams.get("page") ?? "1"));

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

  if (!isForumLoaded) {
    return null;
  }

  return (
    <Stack gap={2}>
      <ListGroup>
        <ListGroupItem>{title}</ListGroupItem>
        {essays.map((essay) => (
          <ListGroupItem key={essay.essayID}>
            <EssayTitleView forumID={forumID} essay={essay} />
          </ListGroupItem>
        ))}
      </ListGroup>
      <Row>
        <Col>
          <PositionInput />
        </Col>
        <Col xs="auto">
          {taehuiLevel >= level && (
            <Button
              variant="success"
              onClick={() => {
                push(`/forum/${forumID}/edit`);
              }}
            >
              <PencilFill />
            </Button>
          )}
        </Col>
      </Row>
    </Stack>
  );
});
