import { useEffect, useMemo, useState } from "react";
import { useParams } from "react-router-dom";
import { Button, Col, Row } from "reactstrap";
import { useTranslation } from "react-i18next";
import { observer } from "mobx-react-lite";
import Swal from "sweetalert2";
import { useTo } from "taehui-ts/fe-utility";
import { getLanguage } from "taehui-ts/language";
import { getMillis } from "taehui-ts/date";

import { wwwAXIOS } from "src/Www";
import { useAvatarStore, useForumStore } from "src/Stores";
import TextView from "src/forum/TextView";
import CommentView from "src/forum/CommentView";
import EssayTitleView from "src/forum/EssayTitleView";
import { EssayViewLoading } from "src/Loading";
import { GetCommentAPI, GetEssayAPI } from "src/wwwAPI";

const EssayView = observer(() => {
  const { t } = useTranslation();

  const {
    forumTitle,
    avatarID,
    avatarName,
    title,
    text,
    hitCount,
    essayBefore,
    essayLater,
    setForumTitle,
    setAvatarID,
    setAvatarName,
    setTitle,
    setText,
    setHitCount,
    setEssayBefore,
    setEssayLater,
    setComments,
  } = useForumStore();
  const { taehuiAvatarID, totem, isTaehui } = useAvatarStore();

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

  const [isLoading, setLoading] = useState(true);
  const [date, setDate] = useState("");

  const to = useTo();

  useEffect(() => {
    (async () => {
      const { data, status } = await wwwAXIOS.get<GetEssayAPI>(
        `/essay/${essayID}`,
        {
          params: { language: getLanguage() },
        },
      );
      if (status === 200) {
        setForumTitle(data.forumTitle);
        setTitle(data.title);
        setText(data.text);
        setDate(data.date);
        setAvatarID(data.avatarID);
        setAvatarName(data.avatarName);
        setHitCount(data.hitCount);
        setEssayBefore(data.essayBefore);
        setEssayLater(data.essayLater);
        setLoading(false);
      }
    })();
  }, [
    essayID,
    setAvatarID,
    setAvatarName,
    setEssayBefore,
    setEssayLater,
    setForumTitle,
    setHitCount,
    setText,
    setTitle,
  ]);

  useEffect(() => {
    (async () => {
      const { data, status } = await wwwAXIOS.get<GetCommentAPI>(
        `/comment/${essayID}`,
      );
      if (status === 200) {
        setComments(data);
      }
    })();
  }, [essayID, setComments]);

  const onWipeEssay = async () => {
    if (
      (
        await Swal.fire({
          title: "Taehui",
          text: t("wipeEssayQuestion"),
          icon: "question",
          showDenyButton: true,
        })
      ).isConfirmed
    ) {
      const { status } = await wwwAXIOS.delete(`/essay/${essayID}`, {
        headers: {
          millis: getMillis(),
          totem,
        },
      });
      if (status === 204) {
        to(`/forum/${forumID}`);
      }
    }
  };

  const onQuit = () => {
    to(`/forum/${forumID}`);
  };

  const isAllowModify = useMemo(
    () => isTaehui || taehuiAvatarID === avatarID,
    [isTaehui, avatarID, taehuiAvatarID],
  );

  if (isLoading) {
    return <EssayViewLoading />;
  }

  return (
    <>
      <Row className="g-0">
        {isAllowModify && (
          <>
            <Col className="m-1" xs="auto">
              <Button color="danger" onClick={onWipeEssay}>
                {t("wipeEssay")}
              </Button>
            </Col>
            <Col className="m-1" xs="auto">
              <Button
                color="warning"
                onClick={() => {
                  to(`/forum/${forumID}/${essayID}/m`);
                }}
              >
                {t("doModifyEssay")}
              </Button>
            </Col>
          </>
        )}
        <Col className="m-1 text-end">
          <Button color="danger" onClick={onQuit}>
            {t("quit")}
          </Button>
        </Col>
      </Row>
      <hr />
      <TextView
        forumTitle={forumTitle}
        title={title}
        text={text}
        avatarID={avatarID}
        avatarName={avatarName}
        date={date}
        hitCount={hitCount}
      />
      {(essayLater || essayBefore) && (
        <>
          <hr />
          {essayLater && (
            <EssayTitleView
              forumID={forumID}
              forumTitle={t("essayLater")}
              essay={essayLater}
            />
          )}
          {essayBefore && (
            <EssayTitleView
              forumID={forumID}
              forumTitle={t("essayBefore")}
              essay={essayBefore}
            />
          )}
        </>
      )}
      <hr />
      <CommentView />
    </>
  );
});

export default EssayView;
