import { useState } from "react";
import { Button, Col, Input, ListGroup, Row } from "reactstrap";
import { useTranslation } from "react-i18next";
import { toast } from "react-toastify";
import ReactTextareaAutosize from "react-textarea-autosize";

import CommentaryItem from "src/commentary/CommentaryItem";
import { CommentaryViewLoading } from "src/Loading";
import useGetCommentary from "src/commentary/useGetCommentary";
import usePostCommentary from "src/commentary/usePostCommentary";

const CommentaryView = () => {
  const { t } = useTranslation();

  const [avatarName, setAvatarName] = useState("");
  const [avatarCipher, setAvatarCipher] = useState("");
  const [inputText, setInputText] = useState("");

  const { data: commentary, isFetched: isCommentaryLoaded } =
    useGetCommentary();
  const { mutate: postCommentary } = usePostCommentary();

  return (
    <>
      <Row className="g-0">
        <Col className="m-1">
          <Input
            placeholder={t("avatarName")}
            valid={!!avatarName}
            invalid={!avatarName}
            onChange={({ target: { value } }) => {
              setAvatarName(value);
            }}
          />
        </Col>
        <Col className="m-1">
          <Input
            valid={!!avatarCipher}
            invalid={!avatarCipher}
            type="password"
            placeholder={t("avatarCipher")}
            onChange={({ target: { value } }) => {
              setAvatarCipher(value);
            }}
          />
        </Col>
      </Row>
      <Row className="g-0">
        <Col className="m-1">
          <ReactTextareaAutosize
            className="form-control"
            value={inputText}
            placeholder={t("text")}
            onChange={({ target: { value } }) => {
              setInputText(value);
            }}
          />
        </Col>
        <Col className="m-1" xs="auto">
          <Button
            color="success"
            onClick={async () => {
              if (avatarName && avatarCipher && inputText) {
                postCommentary({
                  avatarName,
                  avatarCipher,
                  text: inputText,
                });
              } else {
                toast.error(t("failedValidation"));
              }
            }}
          >
            {t("postCommentary")}
          </Button>
        </Col>
      </Row>
      {isCommentaryLoaded ? (
        <Row className="g-0">
          <Col className="m-1">
            <ListGroup>
              {commentary.map((commentary) => (
                <CommentaryItem
                  key={commentary.commentaryID}
                  commentary={commentary}
                />
              ))}
            </ListGroup>
          </Col>
        </Row>
      ) : (
        <CommentaryViewLoading />
      )}
    </>
  );
};

export default CommentaryView;
