import { useState } from "react";
import { IconCheck, IconPlus, IconX } from "@tabler/icons-react";
import { Box, Group, TextInput } from "@mantine/core";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";

const CreateBoardButton = () => {
    const { onCreateBoard } = useBoardsContext();
    const [isWriting, setIsWriting] = useState<boolean>(false);
    const [name, setName] = useState<string>("");

    const onStartCreating = () => {
        setName("");
        setIsWriting(true);
    };

    const onCancelCreating = () => setIsWriting(false);

    const onCompleteCreating = () => {
        if (name) {
            onCreateBoard(name);
        }
        setIsWriting(false);
    };

    return (
        <Box style={{ cursor: "pointer" }}>
            {isWriting ? (
                <Group>
                    <TextInput
                        placeholder={"Название доски"}
                        variant={"unstyled"}
                        value={name}
                        onChange={e => setName(e.target.value)}
                        onKeyDown={e =>
                            e.key === "Enter" && onCompleteCreating()
                        }
                    />
                    <Box onClick={onCompleteCreating}>
                        <IconCheck />
                    </Box>
                    <Box onClick={onCancelCreating}>
                        <IconX />
                    </Box>
                </Group>
            ) : (
                <Box onClick={onStartCreating}>
                    <IconPlus />
                </Box>
            )}
        </Box>
    );
};

export default CreateBoardButton;
