import { observer } from "mobx-react-lite";
import { useTranslation } from "react-i18next";
import { Col, ListGroupItem, Row } from "reactstrap";
import { useParams } from "react-router-dom";
import Swal from "sweetalert2";
import { getDatetime, getMillis } from "taehui-ts/date";

import { useAvatarStore, useForumStore } from "src/Stores";
import { wwwAXIOS } from "src/Www";
import { AutoEssayAPIAutoEssay } from "src/wwwAPI";

const AutoEssayTitleView = observer(
  ({
    autoEssay: { autoEssayID, title, text, date },
  }: {
    autoEssay: AutoEssayAPIAutoEssay;
  }) => {
    const { totem } = useAvatarStore();
    const { setTitle, setText, setAutoEssayID, setAutoEssays } =
      useForumStore();
    const { t } = useTranslation();

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

    return (
      <ListGroupItem
        className="route"
        onClick={async () => {
          const { isConfirmed, isDenied } = await Swal.fire({
            title: t("autoEssay"),
            text: t("setAutoEssayQuestion"),
            icon: "question",
            showDenyButton: true,
            denyButtonText: t("wipeEssay"),
          });

          if (isConfirmed) {
            setTitle(title);
            setText(text);
            setAutoEssayID(autoEssayID);
          }

          if (isDenied) {
            if (
              forumID &&
              (await wwwAXIOS.delete(`/autoEssay/${autoEssayID}`, {
                headers: { millis: getMillis(), totem },
              }))
            ) {
              setAutoEssays(forumID, totem);
            }
          }
        }}
      >
        <Row className="g-0">
          <Col className="m-1">
            <span>{title}</span>
          </Col>
          <Col className="m-1" xs="auto">
            <span>{getDatetime(date)}</span>
          </Col>
        </Row>
      </ListGroupItem>
    );
  },
);

export default AutoEssayTitleView;
