"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = tslib_1.__importStar(require("react"));
const InputAdornment_1 = tslib_1.__importDefault(require("@mui/material/InputAdornment"));
const IconButton_1 = tslib_1.__importDefault(require("@mui/material/IconButton"));
const TextField_1 = tslib_1.__importDefault(require("@mui/material/TextField"));
const api_services_1 = require("@selfcommunity/api-services");
const utils_1 = require("@selfcommunity/utils");
const Media_1 = require("../../../../constants/Media");
const react_intl_1 = require("react-intl");
const material_1 = require("@mui/material");
const INITIAL_STATE = {
    url: '',
    urlError: null
};
exports.default = (props) => {
    // STATE
    const [isCreating, setIsCreating] = (0, react_1.useState)(false);
    const [state, setState] = (0, react_1.useState)(Object.assign({}, INITIAL_STATE));
    const { url, urlError } = state;
    // REFS
    const urlRef = react_1.default.useRef(url);
    urlRef.current = url;
    const timerRef = react_1.default.useRef(null);
    // PROPS
    const { helperText, error, onSuccess } = props, rest = tslib_1.__rest(props, ["helperText", "error", "onSuccess"]);
    // Component update
    (0, react_1.useEffect)(() => {
        // Clear the interval when the component unmounts
        return () => clearTimeout(timerRef.current);
    }, []);
    // HANDLERS
    const handleChange = (event) => {
        const target = event.target;
        const url = target.value.startsWith('h') ? target.value : `https://${target.value}`;
        setState({ url, urlError: (0, utils_1.isValidUrl)(url) ? null : 'validationError' });
    };
    const handleSubmit = (event) => {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        timerRef.current && clearTimeout(timerRef.current);
        setIsCreating(true);
        api_services_1.http
            .request({
            url: api_services_1.Endpoints.ComposerMediaCreate.url(),
            method: api_services_1.Endpoints.ComposerMediaCreate.method,
            data: {
                type: Media_1.MEDIA_TYPE_URL,
                url: urlRef.current
            }
        })
            .then((res) => {
            setState(Object.assign({}, INITIAL_STATE));
            onSuccess && onSuccess(res.data);
        })
            .catch((error) => {
            const _error = (0, api_services_1.formatHttpErrorCode)(error);
            setState({ urlError: _error.urlError ? `urlError.${_error.urlError.error}` : _error.error, url: urlRef.current });
        })
            .then(() => setIsCreating(false));
    };
    const handlePaste = (event) => {
        timerRef.current && clearTimeout(timerRef.current);
        timerRef.current = setTimeout(() => {
            if ((0, utils_1.isValidUrl)(urlRef.current)) {
                handleSubmit(event);
            }
        }, 500);
    };
    /**
     * Renders url text field
     */
    return ((0, jsx_runtime_1.jsx)("form", Object.assign({ method: "post", onSubmit: handleSubmit }, { children: (0, jsx_runtime_1.jsx)(TextField_1.default, Object.assign({ value: url, type: "url", onChange: handleChange, onPaste: handlePaste, error: error || Boolean(urlError), helperText: helperText ||
                (urlError && ((0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: `ui.composer.media.link.add.error.${urlError}`, defaultMessage: `ui.composer.media.link.add.error.${urlError}` }))) || (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.composer.media.link.add.help", defaultMessage: "ui.composer.media.link.add.help" }), disabled: isCreating }, rest, { InputProps: {
                endAdornment: ((0, jsx_runtime_1.jsx)(InputAdornment_1.default, Object.assign({ position: "end" }, { children: (0, jsx_runtime_1.jsx)(material_1.Fade, Object.assign({ in: urlError === null && url !== '' }, { children: (0, jsx_runtime_1.jsx)(IconButton_1.default, Object.assign({ size: "small", disabled: isCreating, type: "submit" }, { children: isCreating ? (0, jsx_runtime_1.jsx)(material_1.CircularProgress, { color: "primary", size: 20 }) : (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.composer.media.link.add.submit", defaultMessage: "ui.composer.media.link.add.submit" }) })) })) })))
            } })) })));
};
