import NoteView, {
  NoteViewLoading,
} from "@/app/[language]/note/components/NoteView";
import useGetNote from "@/app/[language]/note/query/useGetNote";
import { useNoteStore, useSiteStore } from "@/state/Stores";
import { observer } from "mobx-react-lite";
import { useLayoutEffect, useState } from "react";
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 { useWindowArea } from "taehui-lib/fe-utilities";

export default observer(() => {
  const { wantAvatar, viewUnit } = useNoteStore();
  const { siteAvatarID } = useSiteStore();

  const {
    data: { notes },
    isFetched: isNoteLoaded,
  } = useGetNote();

  const { windowLength } = useWindowArea();
  const [table, setTable] = useState(1);

  useLayoutEffect(() => {
    setTable(windowLength < 992 ? 1 : 2);
  }, [windowLength]);

  return (
    <Row>
      {[...Array(table).keys()].map((i) => {
        if (isNoteLoaded) {
          return (
            <Col key={i}>
              <ListGroup>
                {notes
                  .slice((viewUnit / table) * i, (viewUnit / table) * (i + 1))
                  .map(
                    ({
                      noteID,
                      artist,
                      title,
                      genre,
                      levelText,
                      level,
                      topCount,
                      totalCount,
                    }) => (
                      <ListGroupItem key={noteID}>
                        <NoteView
                          noteID={noteID}
                          artist={artist}
                          title={title}
                          genre={genre}
                          levelText={levelText}
                          level={level}
                          topCount={topCount}
                          totalCount={totalCount}
                          wantAvatarID={wantAvatar ? undefined : siteAvatarID}
                          wantAvatarName={wantAvatar}
                        />
                      </ListGroupItem>
                    ),
                  )}
              </ListGroup>
            </Col>
          );
        }

        return (
          <Col key={i}>
            <ListGroup>
              {[...Array(viewUnit).keys()].map((i) => (
                <ListGroupItem key={i}>
                  <NoteViewLoading />
                </ListGroupItem>
              ))}
            </ListGroup>
          </Col>
        );
      })}
    </Row>
  );
});
