import { useState } from "react";
import { Col, Collapse, ListGroupItem, Row, Spinner } from "reactstrap";
import { runInAction } from "mobx";
import { observer } from "mobx-react-lite";

import WwwLevelData from "src/avatar/WwwLevelData";
import { wwwAXIOS } from "src/Www";
import { toDate } from "src/Utility";
import { AvatarWwwLevelsAPI, LevelAPI } from "src/wwwAPI";

export default observer(({ levelID, title, date }: AvatarWwwLevelsAPI) => {
  const [isWwwLevelDataOpened, setWwwLevelDataOpened] = useState(false);
  const [isLoading, setLoading] = useState(false);
  const [wwwLevelData, setWwwLevelData] = useState<LevelAPI>();

  return (
    <ListGroupItem>
      <Row
        className="g-0 route"
        onClick={async () => {
          if (isWwwLevelDataOpened) {
            setWwwLevelDataOpened(false);
          } else {
            setLoading(true);
            const { status, data } = await wwwAXIOS.get<LevelAPI>("/level", {
              params: {
                levelID,
              },
            });
            if (status === 200) {
              runInAction(() => {
                setWwwLevelData(data);
                setWwwLevelDataOpened(true);
                setLoading(false);
              });
            }
          }
        }}
      >
        <Col className="m-1" xs="auto">
          <span>{title}</span> {isLoading && <Spinner size="sm" />}
          <br />
          {date && <span className="fittedText">{toDate(date)}</span>}
        </Col>
      </Row>
      <Collapse isOpen={isWwwLevelDataOpened}>
        {wwwLevelData && <WwwLevelData wwwLevelData={wwwLevelData} />}
      </Collapse>
    </ListGroupItem>
  );
});
