import { useEffect, useState } from "react";
import { Col, Row } from "reactstrap";
import { useParams } from "react-router-dom";
import { getLanguage } from "taehui-ts/language";
import { useWindowArea } from "taehui-ts/fe-utility";

import ForumItem from "src/forum/ForumItem";
import { ForumsViewLoading } from "src/Loading";
import { wwwAXIOS } from "src/Www";
import { GetForumsAPI } from "src/wwwAPI";

const ForumsView = () => {
  const [forums, setForums] = useState<GetForumsAPI>([]);
  const [isLoading, setLoading] = useState(true);

  const line = useWindowArea().windowLength < 992 ? 1 : 2;

  const { forumGroup } = useParams<{ forumGroup: string }>();

  useEffect(() => {
    (async () => {
      const { data, status } = await wwwAXIOS.get<GetForumsAPI>(
        forumGroup ? `/forums/${forumGroup}` : "/forums",
        {
          params: { language: getLanguage() },
        },
      );
      if (status === 200) {
        setForums(data);
        setLoading(false);
      }
    })();
  }, [forumGroup]);

  if (isLoading) {
    return <ForumsViewLoading />;
  }

  return (
    <>
      {[...Array(Math.ceil(forums.length / line)).keys()].map((i) => (
        <Row key={i} className="g-0">
          {forums.slice(line * i, line * i + line).map((forum) => (
            <Col key={forum.forumID} className="m-1">
              <ForumItem forum={forum} />
            </Col>
          ))}
        </Row>
      ))}
    </>
  );
};

export default ForumsView;
