/**
 * @file CommentsSection.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

import {CircularProgress, Grid, IconButton, Paper, TextField, Tooltip, Typography} from "@mui/material";
import SendIcon from '@mui/icons-material/Send';
import React, {useEffect, useState} from "react";
import {axiosGet, axiosPost} from "../../services/AxiosService";
import Comment from "./Comment";
import {useAuth} from "../../services/AuthMiddleware";
import Paginator from "../common/Paginator";

function CommentsSection(props) {
    const presetID = props.presetID;
    const [comments, setComments] = React.useState();
    const [editedText, setEditedText] = React.useState("");
    const [page, setPage] = useState(1);
    const [pageCount, setPageCount] = useState(1);
    const itemsPerPage = 10;
    const auth = useAuth();

    useEffect(() => {
        const filter = {preset: presetID, owners: true};
        filter["max_items"] = itemsPerPage;
        filter["page"] = page - 1;

        axiosGet("/comments", filter).then((res) => {
            setPageCount(Math.ceil(res.data.count / itemsPerPage));
            setComments(res.data.items);
        }).catch((e) => {
            console.error(e);
        });
    }, [presetID, page]);

    const buttonClicked = async () => {
        const res = await axiosPost("/comments", {
            ownerID: auth.user.id,
            presetID: presetID,
            text: editedText
        });
        setComments(arr => [res.data, ...arr]);
        setEditedText("");
    }

    const commentRemoved = (id) => {
        setComments(comments.filter((item) => {
            return item.id !== id;
        }));
    }

    return (<Paper elevation={2} sx={{padding: 1}}>

        <Typography variant={"h6"}>Komentáře</Typography>

        {!!comments ? <Grid container rowSpacing={1} columns={{xs: 1}}>
                <Grid item xs={1}>
                    <Grid container columns={{xs: 3}}>
                        <Grid item xs={2}>
                            <Typography>Přidat komentář </Typography>
                        </Grid>

                        <Grid item xs={1} sx={{textAlign: "right"}}>
                            <Tooltip title={"Odeslat"} followCursor>
                                <IconButton onClick={buttonClicked} size={"small"} disabled={editedText?.length === 0}>
                                    <SendIcon fontSize={"inherit"}/>
                                </IconButton>
                            </Tooltip>
                        </Grid>
                    </Grid>

                    <TextField multiline maxRows={15} fullWidth
                               value={editedText}
                               onChange={(e) => setEditedText(e.target.value)}
                    />
                </Grid>
                {Array.from(comments).map((comment, _) => {
                    return (<Grid item xs={1} key={comment.id}>
                                <Comment comment={comment} key={comment.id} onRemove={commentRemoved}/>
                            </Grid>)
                })}
            </Grid>
            :
            <CircularProgress/>
        }

        <Paginator page={page} pageCount={pageCount} pageChanged={(val) => setPage(val)}/>

    </Paper>);
}


export default CommentsSection;
