import { useEffect, useState } from "react";
import { Col, Row } from "reactstrap";
import { useTranslation } from "react-i18next";
import { getDatetime } from "taehui-ts/date";

import { wwwAXIOS } from "src/Www";
import { LatestAvatarViewLoading } from "src/Loading";
import AvatarTitle from "src/taehui/AvatarTitle";
import { GetLatestAvatarAPI } from "src/wwwAPI";

const LatestAvatarsView = () => {
  const [isLoading, setLoading] = useState(true);
  const [latestAvatars, setLatestAvatars] = useState<GetLatestAvatarAPI[]>([]);

  const { t } = useTranslation();

  useEffect(() => {
    (async () => {
      const { status, data } =
        await wwwAXIOS.get<GetLatestAvatarAPI[]>("/avatar/latest");

      if (status === 200) {
        setLatestAvatars(data);
        setLoading(false);
      }
    })();
  }, []);

  return (
    <Row className="g-0">
      {latestAvatars.map((latestAvatar, i) => {
        return (
          <Col className="m-1" key={i}>
            <h5>{t(`latestAvatarsView${i}`)}</h5>
            {isLoading ? (
              <LatestAvatarViewLoading />
            ) : (
              latestAvatar.map(({ avatarID, avatarName, date }) => {
                return (
                  <Row className="g-0" key={avatarID}>
                    <AvatarTitle avatarID={avatarID} avatarName={avatarName}>
                      <span>{getDatetime(date)}</span>
                    </AvatarTitle>
                  </Row>
                );
              })
            )}
          </Col>
        );
      })}
    </Row>
  );
};

export default LatestAvatarsView;
