import { __rest } from "tslib";
import { jsx as _jsx } from "react/jsx-runtime";
import React, { useEffect, useState } from 'react';
import InputAdornment from '@mui/material/InputAdornment';
import IconButton from '@mui/material/IconButton';
import TextField from '@mui/material/TextField';
import { Endpoints, formatHttpErrorCode, http } from '@selfcommunity/api-services';
import { isValidUrl } from '@selfcommunity/utils';
import { MEDIA_TYPE_URL } from '../../../../constants/Media';
import { FormattedMessage } from 'react-intl';
import { CircularProgress, Fade } from '@mui/material';
const INITIAL_STATE = {
    url: '',
    urlError: null
};
export default (props) => {
    // STATE
    const [isCreating, setIsCreating] = useState(false);
    const [state, setState] = useState(Object.assign({}, INITIAL_STATE));
    const { url, urlError } = state;
    // REFS
    const urlRef = React.useRef(url);
    urlRef.current = url;
    const timerRef = React.useRef(null);
    // PROPS
    const { helperText, error, onSuccess } = props, rest = __rest(props, ["helperText", "error", "onSuccess"]);
    // Component update
    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: isValidUrl(url) ? null : 'validationError' });
    };
    const handleSubmit = (event) => {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        timerRef.current && clearTimeout(timerRef.current);
        setIsCreating(true);
        http
            .request({
            url: Endpoints.ComposerMediaCreate.url(),
            method: Endpoints.ComposerMediaCreate.method,
            data: {
                type: MEDIA_TYPE_URL,
                url: urlRef.current
            }
        })
            .then((res) => {
            setState(Object.assign({}, INITIAL_STATE));
            onSuccess && onSuccess(res.data);
        })
            .catch((error) => {
            const _error = 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 (isValidUrl(urlRef.current)) {
                handleSubmit(event);
            }
        }, 500);
    };
    /**
     * Renders url text field
     */
    return (_jsx("form", Object.assign({ method: "post", onSubmit: handleSubmit }, { children: _jsx(TextField, Object.assign({ value: url, type: "url", onChange: handleChange, onPaste: handlePaste, error: error || Boolean(urlError), helperText: helperText ||
                (urlError && (_jsx(FormattedMessage, { id: `ui.composer.media.link.add.error.${urlError}`, defaultMessage: `ui.composer.media.link.add.error.${urlError}` }))) || _jsx(FormattedMessage, { id: "ui.composer.media.link.add.help", defaultMessage: "ui.composer.media.link.add.help" }), disabled: isCreating }, rest, { InputProps: {
                endAdornment: (_jsx(InputAdornment, Object.assign({ position: "end" }, { children: _jsx(Fade, Object.assign({ in: urlError === null && url !== '' }, { children: _jsx(IconButton, Object.assign({ size: "small", disabled: isCreating, type: "submit" }, { children: isCreating ? _jsx(CircularProgress, { color: "primary", size: 20 }) : _jsx(FormattedMessage, { id: "ui.composer.media.link.add.submit", defaultMessage: "ui.composer.media.link.add.submit" }) })) })) })))
            } })) })));
};
