import { useMemo } from "react";
import { observer } from "mobx-react-lite";

import { CommentAPIComment } from "src/wwwAPI";
import CommentItem from "src/note/CommentItem";
import { formatText, getDefaultAvatarID } from "src/Utility";
import { useSiteStore } from "src/Stores";

export default observer(
  ({
    comments,
    wantAvatarID,
    wantAvatarName,
  }: {
    comments: CommentAPIComment[];
    wantAvatarID?: string;
    wantAvatarName?: string;
  }) => {
    const { siteAvatarID } = useSiteStore();

    const avatarPlace = useMemo(
      () =>
        comments.findIndex(
          ({ avatarID }) => avatarID === getDefaultAvatarID(siteAvatarID),
        ) + 1,
      [comments, siteAvatarID],
    );

    return (
      <>
        {avatarPlace > 0 && (
          <>
            <span className="avatarPlace">＃{formatText(avatarPlace)}</span>
            <span>／{formatText(comments.length)}</span>
          </>
        )}
        {comments.map(
          ({
            date,
            avatarID,
            avatarName,
            stand,
            band,
            point,
            commentary,
            isP,
            judgmentMode,
            hitPointsMode,
            isPaused,
          }) => (
            <CommentItem
              key={avatarID}
              date={date}
              avatarID={avatarID}
              avatarName={avatarName}
              stand={stand}
              band={band}
              point={point}
              isP={isP}
              commentary={commentary}
              isTargetAvatar={
                !!(wantAvatarID && wantAvatarID === avatarID) ||
                !!(wantAvatarName && wantAvatarName === avatarName)
              }
              judgmentMode={judgmentMode}
              hitPointsMode={hitPointsMode}
              isPaused={isPaused}
            />
          ),
        )}
      </>
    );
  },
);
