import { useMemo, useState } from "react";
import { observer } from "mobx-react-lite";
import { useParams } from "react-router-dom";
import ReactTextareaAutosize from "react-textarea-autosize";
import Swal from "sweetalert2";
import { Button, Col, Collapse, Row } from "reactstrap";
import { useTranslation } from "react-i18next";
import { getDatetime, getMillis } from "taehui-ts/date";

import { useAvatarStore } from "src/Stores";
import { wwwAXIOS } from "src/Www";
import AvatarTitle from "src/taehui/AvatarTitle";
import { toast } from "react-toastify";

const CommentItem = observer(
  ({
    commentID,
    text,
    avatarID,
    avatarName,
    date,
    level,
  }: {
    commentID: number;
    text: string;
    date: string;
    avatarID: string;
    avatarName: string;
    level: number;
  }) => {
    const { t } = useTranslation();
    const { totem, taehuiAvatarID, taehuiAvatarName, isTaehui } =
      useAvatarStore();

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

    const [inputText, setInputText] = useState("");
    const [inputTargetText, setInputTargetText] = useState("");
    const [isTargetOpened, setTargetOpened] = useState(false);

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

    return (
      <div style={{ marginLeft: `${level * 3.5}rem` }}>
        <Row key={commentID} className="g-0">
          <AvatarTitle avatarID={avatarID} avatarName={avatarName}>
            <div
              className="route"
              onClick={() => {
                if (totem && !isTargetOpened) {
                  setTargetOpened(true);
                }
              }}
            >
              {isTargetOpened && isAllowModify ? (
                <Row className="g-0">
                  <Col className="m-1">
                    <ReactTextareaAutosize
                      className="form-control"
                      placeholder={t("text")}
                      defaultValue={text}
                      onChange={({ target: { value } }) => {
                        setInputText(value);
                      }}
                    />
                  </Col>
                  <Col className="m-1" xs="auto">
                    <Button
                      color="warning"
                      onClick={async () => {
                        if (inputText) {
                          const { status } = await wwwAXIOS.put(
                            `/comment/${commentID}`,
                            { text: inputText },
                            {
                              headers: {
                                millis: getMillis(),
                                totem,
                              },
                            },
                          );
                          if (status === 204) {
                            window.location.reload();
                          }
                        } else {
                          toast.error(t("failedValidation"));
                        }
                      }}
                    >
                      {t("doModifyComment")}
                    </Button>
                  </Col>
                  <Col className="m-1" xs="auto">
                    <Button
                      color="danger"
                      onClick={async () => {
                        if (
                          (
                            await Swal.fire({
                              title: "Taehui",
                              text: t("wipeCommentQuestion"),
                              icon: "question",
                              showDenyButton: true,
                            })
                          ).isConfirmed
                        ) {
                          const { status } = await wwwAXIOS.delete(
                            `/comment/${commentID}`,
                            {
                              headers: {
                                millis: getMillis(),
                                totem,
                              },
                            },
                          );
                          if (status === 204) {
                            window.location.reload();
                          }
                        }
                      }}
                    >
                      {t("wipeComment")}
                    </Button>
                  </Col>
                </Row>
              ) : (
                <span className="ln">{text}</span>
              )}
            </div>
          </AvatarTitle>
          <Col className="m-1" xs="auto">
            <span>{getDatetime(date)}</span>
          </Col>
        </Row>
        <Collapse isOpen={isTargetOpened} style={{ marginLeft: "3.5rem" }}>
          <Row className="g-0">
            <AvatarTitle
              avatarID={taehuiAvatarID}
              avatarName={taehuiAvatarName}
            >
              <Row className="g-0">
                <Col className="m-1">
                  <ReactTextareaAutosize
                    className="form-control"
                    placeholder={t("text")}
                    value={inputTargetText}
                    onChange={({ target: { value } }) => {
                      setInputTargetText(value);
                    }}
                  />
                </Col>
                <Col className="m-1" xs="auto">
                  <Button
                    color="success"
                    onClick={async () => {
                      if (inputTargetText) {
                        const { status } = await wwwAXIOS.post(
                          `/comment/${essayID}`,
                          { targetCommentID: commentID, text: inputTargetText },
                          {
                            headers: {
                              millis: getMillis(),
                              totem,
                            },
                          },
                        );
                        if (status === 201) {
                          window.location.reload();
                        }
                      } else {
                        toast.error(t("failedValidation"));
                      }
                    }}
                  >
                    {t("postComment")}
                  </Button>
                </Col>
              </Row>
            </AvatarTitle>
          </Row>
        </Collapse>
      </div>
    );
  },
);

export default CommentItem;
