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

import React, {useEffect, useState} from "react";
import {Box, IconButton, TextField, Tooltip, Typography} from "@mui/material";
import SaveIcon from "@mui/icons-material/Save";
import EditIcon from "@mui/icons-material/Edit";

function EditableText(props) {
    const [text, setText] = useState();
    const [editText, setEditText] = useState();
    const [isEditing, setEditing] = useState(false);
    const limit = props.limit || 150;
    const maxRows = props.rows || 0;
    const textVariant = props.textVariant;
    const textColor = props.color;

    useEffect(() => {
        setText(props.text);
        setEditText(props.text);
    }, [props]);

    const textChanged = (e) => {
        const val = e.target.value;
        if (val.length > limit) {
            // alert("Limit!");
            return;
        }
        setEditText(val);
    }

    const editButtonClicked = () => {
        if (editText !== text) {
            setText(editText);
            props.saveFce(editText);
        }
        setEditing(!isEditing);
    }

    return (<Box sx={{display: "inline-flex", flexWrap: "nowrap", width: "100%"}}>
        <Box sx={{flexGrow: 1}}>
            {isEditing ?
                <TextField multiline={maxRows > 1} maxRows={maxRows} fullWidth={true}
                           variant={"standard"}
                           value={editText}
                           onChange={(e) => textChanged(e)}
                           helperText={editText?.length >= limit ? "Dosažen limit znaků!" : ""}
                           color={editText?.length >= limit ? "warning" : "primary"}/>
                :
                <Typography variant={textVariant} display={"inline"}
                            sx={{whiteSpace: 'pre-line', overflowWrap: 'anywhere'}}
                            color={textColor}>
                    {text}
                </Typography>
            }
        </Box>
        {props.canEdit && <div>
            <Tooltip title={isEditing ? "Uložit" : "Editovat"} followCursor>
                             <IconButton onClick={editButtonClicked} size={"small"} disabled={isEditing && editText?.length === 0}>
                                {isEditing ? <SaveIcon fontSize={"inherit"}/> : <EditIcon fontSize={"inherit"}/>}
                            </IconButton>
            </Tooltip>
                        </div>
        }
        <br/>
    </Box>);
}

export default EditableText;