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

import {Button, Paper, Typography} from "@mui/material";
import React, {useEffect, useState} from "react";
import {useNavigate} from "react-router-dom";
import EditableText from "../common/EditableText";
import {axiosPatch, axiosRemove} from "../../services/AxiosService";
import DialogYesNo from "../common/DialogYesNo";

function PublicPresetDetail(props) {
    const navigate = useNavigate();
    const preset = props.preset;
    const [dialogOpen, setDialogOpen] = React.useState(false);
    const [editingEnabled, setEditingEnabled] = useState(false);

    useEffect(() => {
        setEditingEnabled(props.editingEnabled || false);
    }, [props]);

    const titleSave = async (text) => {
        const res = await axiosPatch("/presets/", {id: preset.id, name: text})
    }

    const descSave = async (text) => {
        const res = await axiosPatch("/presets/", {id: preset.id, shortDescription: text});
    }

    const removePreset = async () => {
        setDialogOpen(false)
        const res = await axiosRemove("/presets/" + preset.id);
        navigate("/presets");
    }

    return (<>
        <DialogYesNo fceYes={removePreset}
                     fceNo={() => setDialogOpen(false)}
                     title={"Smazat přednastavení?"}
                     description={"Potvrdit smazání přednastavení"}
                     isOpen={dialogOpen}
        />
        {preset !== null ?
            <Paper elevation={2} sx={{padding: 1}}>
                <EditableText text={preset.name} saveFce={titleSave} textVariant={"h6"} limit={50} canEdit={editingEnabled}/>
                <Typography variant={"subtitle2"}>{preset?.owner?.name}</Typography>
                <EditableText text={preset.shortDescription} saveFce={descSave} rows={7}
                              color="text.secondary" textVariant={"subtitle1"}
                              limit={200} canEdit={editingEnabled}/>

                {editingEnabled &&
                    <Button size={"small"} onClick={() => setDialogOpen(true)} sx={{color: "red"}}>Smazat</Button>
                }

            </Paper>
            :
            <div/> }
    </>);
}


export default PublicPresetDetail;
