import React, { useState, useEffect, Fragment } from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import CapTab from '@capillarytech/cap-ui-library/CapTab';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapModal from '@capillarytech/cap-ui-library/CapModal';
import style, { CapModalStyles } from './style';
import withStyles from '../../../../hoc/withStyles';
import { TEXT, TEMPLATE } from '../constants';
import { getTabPanes } from './utils';
import messages from './messages';
import { CAP_SPACE_16, CAP_SPACE_08 } from '@capillarytech/cap-ui-library/styled/variables';

const StyledCapModal = withStyles(CapModal, CapModalStyles);

export const LineWrapper = ({
    className,
    index,
    deleteWrapper,
    selectedType,
    shiftUp,
    shiftDown,
    lineWrappers,
    intl,
    ...rest
}) => {

    const [activeKey, updateActiveKey] = useState(TEXT);
    const [selectedKey, updateSelectedKey] = useState(TEXT);
    const [isConfirmModalVisible, togglePopup] = useState(false);

    useEffect(() => {
        updateActiveKey(selectedType === 'template' ? TEMPLATE : selectedType);
    }, [selectedType]);

    const onTabChange = (type) => {
        const { content = {} } = rest;
        const {
            originalContentUrl,
            previewImageUrl,
            stickerUrl,
            animatedStickerUrl,
            selectedSticker,
            stickerId,
            packageId,
            messageContent,
            messageTitle,
            baseUrl,
            selectedTemplate,
            template,
            altText,
            videoSrc,
        } = content;

        const isTouched  = (
            originalContentUrl
            || previewImageUrl
            || stickerUrl
            || animatedStickerUrl
            || selectedSticker
            || stickerId
            || packageId
            || messageTitle
            || messageContent
            || baseUrl
            || selectedTemplate
            || template
            || altText
            || videoSrc
        );
        if (!isTouched) {
            updateActiveKey(type);
            rest.updateMessageState({
                isError: true,
                index,
                type,
            });
        } else {
            togglePopup(true);
            rest.deleteUploadedImgList(index);
            updateSelectedKey(type);
            updateActiveKey(activeKey);
        }
    }

    const saveChangesOnLeave = () => {
        updateActiveKey(selectedKey);
        rest.updateMessageState({
            isError: true,
            index,
            type: selectedKey,
        });
        togglePopup(false);
    }

    const discardChangesOnLeave = () => {
        updateActiveKey(activeKey);
        togglePopup(false);
    }

    const operations = (
        <>
            <CapButton
                type="flat"
                onClick={() => shiftUp(index)}
                disabled={index === 0 || rest.isFullMode}
                style={{ padding: 0 }}
            >
                <CapIcon type="back" size="s" style={{ transform: 'rotate(90deg)'}}/>
            </CapButton>
            <CapButton
                type="flat"
                onClick={() => shiftDown(index)}
                style={{ padding: `0 0 0 ${CAP_SPACE_08}` }}
                disabled={(index+1) === lineWrappers || rest.isFullMode}
            >
                <CapIcon type="back" size="s"  style={{ transform: 'rotate(270deg)'}}/>
            </CapButton>
            <CapButton
                type="flat"
                onClick={() => deleteWrapper(index)}
                disabled={rest.isFullMode || lineWrappers === 1}
                style={{ padding: `0 ${CAP_SPACE_16} 0 ${CAP_SPACE_16}`, marginRight: -20 }}
            >
                <CapIcon type="close" size="s"/>
            </CapButton>
        </>
    );

    return (
        <div className={className}>
            <CapTab
                defaultActiveKey={TEXT}
                activeKey={activeKey}
                tabBarExtraContent={rest.isFullMode ? <Fragment /> : operations}
                onChange={onTabChange}
                panes={getTabPanes({ ...rest, index, activeKey, formatMessage: intl.formatMessage, isFullMode: rest.isFullMode })}
            />
            <StyledCapModal
                title={intl.formatMessage(messages.changeModalTitle)}
                visible={isConfirmModalVisible}
                onOk={saveChangesOnLeave}
                onCancel={discardChangesOnLeave}
                centered
                okText={intl.formatMessage(messages.modalSaveChangesButtonLabel)}
                cancelText={intl.formatMessage(messages.modalDiscardChangesButtonLabel)}
                closeText={intl.formatMessage(messages.modalDiscardChangesButtonLabel)}
                width="450px"
            >
                <FormattedMessage {...messages.changeModalDescription} />
                <div className="modal-description">
                    <FormattedMessage {...messages.changeModalLabel} />
                </div>
            </StyledCapModal>
        </div>
    )
}

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