import React,  { useState, useEffect } from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import get from 'lodash/get';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapDrawer from '@capillarytech/cap-ui-library/CapDrawer';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapImage from '@capillarytech/cap-ui-library/CapImage';
import CapTab from '@capillarytech/cap-ui-library/CapTab';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import { FONT_COLOR_05 } from '@capillarytech/cap-ui-library/styled/variables';

import style from './style';
import withStyles from '../../../../hoc/withStyles';
import messages from './messages';

import { getTabPanes } from './utils';

export const LineSticker = ({
    actions,
    Line,
    className,
    id,
    intl: { formatMessage },
    inheritedTitleStyle,
    isFullMode,
    updateMessageState,
    index,
    activeKey,
    content,
}) => {
    if (activeKey !== 'sticker') {
        return null;
    }

    const [lineStickers, updateStickerList] = useState([]);
    const [messageTitle, updateTextMessageTitle] = useState('');
    const [errorMessageTitle, updateErrorMessageTitle] = useState(false);
    const [isStickerDrawerOpen, toggleStickerDrawer] = useState(false);
    const [selectedSticker, updateSelectedStickerDetails] = useState();

    useEffect(() => {
        actions.getLineStickers();
    }, []);

    useEffect(() => {
        const { messageTitle = '', selectedSticker = {}, type } = content;
        if (selectedSticker.stickerUrl && type === 'sticker') {
            updateTextMessageTitle(messageTitle);
            updateSelectedStickerDetails(selectedSticker);
        }
    }, [content]);

    useEffect(() => {
        updateStickerList(get(Line, 'lineStickers.response.metaEntities', []));
    }, [Line]);

    useEffect(() => {
        if (selectedSticker && (isFullMode ? messageTitle : true)) {
            updateMessageState({
                isError: !selectedSticker || !(isFullMode ? messageTitle : true) || errorMessageTitle,
                selectedSticker,
                messageTitle,
                index,
                type: 'sticker',
                messageType: 'selectedSticker',
            });
        }
    }, [errorMessageTitle, selectedSticker, messageTitle]);

    const updateTextTitleError = (value) => {
        let errorMessage = false;
        if (value === '') {
            errorMessage = formatMessage(messages.emptyTitleErrorMessage);
            updateMessageState({
                isError: true,
                selectedSticker,
                messageTitle: '',
                index,
                type: 'sticker',
                messageType: 'selectedSticker',
            });
        }
        updateErrorMessageTitle(errorMessage);
    }

    const onTextTitleChange = ({ target: { value } }) => {
        updateTextMessageTitle(value);
        updateTextTitleError(value);
    }

    const removeSelectedSticker = () => {
        updateSelectedStickerDetails();
        updateMessageState({
            isError: true,
            selectedSticker: undefined,
            messageTitle,
            index,
            type: 'sticker',
            messageType: 'selectedSticker',
        });
    }

    const getLineStickerSection = () => {
        if  (selectedSticker) {
            return (
                <>
                    <CapImage
                        src={selectedSticker.stickerUrl}
                        rest={{
                            height: 70,
                            onMouseOut: e => (e.currentTarget.src = selectedSticker.stickerUrl),
                            onMouseOver: e => (e.currentTarget.src = selectedSticker.animatedStickerUrl ||  selectedSticker.stickerUrl),
                        }}
                    />
                    <CapButton
                        type="link"
                        style={{ padding: 0, top: -34, right: 8 }}
                        onClick={removeSelectedSticker}
                    >
                        <CapIcon type="close-circle" size="s" theme="filled" />
                    </CapButton>
                </>
            );
        }
        return (
            <CapButton
                onClick={() => toggleStickerDrawer(true)}
                type="secondary"
            >
                <FormattedMessage {...messages.selectStickersLabels} />
            </CapButton>
        );
    }

    const onStickerSelect = (definition) => {
        updateSelectedStickerDetails(definition);
        updateMessageState({
            isError: !definition || !(isFullMode ? messageTitle : true) || errorMessageTitle,
            selectedSticker: definition,
            messageTitle,
            index,
            type: 'sticker',
            messageType: 'selectedSticker',
        });
        toggleStickerDrawer(false);
    }

    const getStickerSection = () => {
        return (
            <CapTab 
                panes={getTabPanes({ lineStickers, onStickerSelect })}
            />
        )
    }

    const getStickerDrawerContent = () => {
        return (
            <>
                <CapHeading type="h3">
                    {formatMessage(messages.stickerDrawerTitle)}
                </CapHeading>
                {getStickerSection()}
            </>
        );
    }

    return (
        <div className={className}>
            {
                isFullMode
                ? (
                    <CapInput
                        id={`${id}_input`}
                        onChange={onTextTitleChange}
                        errorMessage={errorMessageTitle}
                        className="sticker-template-title"
                        style={inheritedTitleStyle || {}}
                        placeholder={formatMessage(messages.textMessageTitlePlaceholder)}
                        defaultValue={messageTitle || ''}
                        value={messageTitle || ''}
                        size="default"
                        label={formatMessage(messages.textMessageTitleLabel)}
                    />
                )
                : null
            }
            <CapHeading type="h3" className="sticker-label">
                <FormattedMessage {...messages.stickerDrawerTitle} />
                {
                    selectedSticker
                    ? (
                        <CapButton
                            onClick={removeSelectedSticker}
                            type="link"
                            style={{
                                padding: 0,
                                marginLeft: 400,
                                color: FONT_COLOR_05,
                                height: 'auto',
                            }}
                        >
                            <FormattedMessage {...messages.changeStickerButtonLabel} />
                        </CapButton>
                    )
                    : null
                }
            </CapHeading>
            <div className="sticker-content">
                {
                    getLineStickerSection()
                }
            </div>
            <CapDrawer
                content={getStickerDrawerContent()}
                visible={isStickerDrawerOpen}
                width={430}
                onClose={() => toggleStickerDrawer(false)}
            />
        </div>
    )
}

export default injectIntl(withStyles(LineSticker, style));