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

import {axiosGet, axiosPatch} from "../../services/AxiosService";
import React, {useEffect, useState} from "react";
import {useParams} from "react-router-dom";
import Preset from "../../components/presets/Preset";
import {Grid, Paper, Typography} from "@mui/material";
import CommentsSection from "../../components/comments/CommentsSection";
import PublicPresetDetail from "../../components/presets/PublicPresetDetail";
import {useAuth} from "../../services/AuthMiddleware";
import {isAdmin} from "../../util/AuthInfo";
import EditableText from "../../components/common/EditableText";

function PublicPresetDetailPage() {
    const {id} = useParams()
    const [publicPreset, setPublicPreset] = useState(null);
    const [comments, setComments] = useState();
    const [editingEnabled, setEditingEnabled] = useState(false);
    const auth = useAuth();

    useEffect(() => {
        axiosGet("/presets/" + id, {data: true, owners: true}).then((res) => {
            setPublicPreset(res.data);
        }).catch((e) => {
            console.error(e);
        });
    }, [id]);

    useEffect(() => {
        setEditingEnabled(isAdmin(auth?.user) || publicPreset?.ownerId === auth?.user?.id);
    }, [publicPreset]);

    const longDescSave = async (text) => {
        const res = await axiosPatch("/presets/", {id: publicPreset.id, description: text});
    }

    return (<Grid container columns={{xs: 1, md: 2}} spacing={2}>
        <Grid item xs={1}>
            <PublicPresetDetail preset={publicPreset} editingEnabled={editingEnabled}/>
        </Grid>

        <Grid item xs={1}>
            <Preset preset={publicPreset?.data} editingEnabled={editingEnabled}/>
        </Grid>

        <Grid item xs={1}>
            <Paper elevation={2} sx={{padding: 1, minHeight: 133}}>
                <Typography variant={"h6"}>Dlouhý popis</Typography>
                <EditableText text={publicPreset?.description} rows={40} saveFce={longDescSave}
                              textVariant={"normal"} limit={800} canEdit={editingEnabled}/>
            </Paper>
        </Grid>

        <Grid item xs={1}>
            <CommentsSection comments={comments} presetID={publicPreset?.id}/>
        </Grid>



    </Grid>);
}


export default PublicPresetDetailPage