import React, { FC, ReactNode, useEffect, useRef, useState } from "react";
import { TextInput } from "@mantine/core";
import { Styles } from "@mantine/core/lib/core/styles-api/styles-api.types";

type Props = {
    defaultValue?: string;
    onComplete: (value: string) => void;
    placeholder?: string;
    getChildren: (startEditing: () => void) => ReactNode;
    inputStyles?: Styles<any>;
};

const InPlaceInputDesktop: FC<Props> = ({
    onComplete,
    placeholder,
    inputStyles,
    getChildren,
    defaultValue = "",
}) => {
    const [isWriting, setIsWriting] = useState<boolean>(false);
    const [value, setValue] = useState<string>(defaultValue);
    const inputRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
        if (isWriting && inputRef.current) {
            inputRef.current.focus();
        }
    }, [isWriting]);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (
                isWriting &&
                inputRef.current &&
                !inputRef.current.contains(event.target as Node)
            ) {
                onCompleteCreating();
            }
        };

        document.addEventListener("mousedown", handleClickOutside);
        return () =>
            document.removeEventListener("mousedown", handleClickOutside);
    }, [isWriting, value]);

    const onStartCreating = () => {
        setValue(defaultValue);
        setIsWriting(true);
    };

    const onCancelCreating = () => {
        setValue(defaultValue);
        setIsWriting(false);
    };

    const onCompleteCreating = () => {
        const localValue = value.trim();
        if (localValue) {
            onComplete(localValue);
        }
        setIsWriting(false);
    };

    if (isWriting) {
        return (
            <TextInput
                ref={inputRef}
                placeholder={placeholder}
                variant={"unstyled"}
                value={value}
                onChange={e => setValue(e.target.value)}
                onKeyDown={e => {
                    e.stopPropagation();
                    if (e.key === "Enter") onCompleteCreating();
                    if (e.key === "Escape") onCancelCreating();
                }}
                styles={inputStyles}
                miw={150}
            />
        );
    }

    return getChildren(onStartCreating);
};

export default InPlaceInputDesktop;
