import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import Icon from '../icon/Icon';
import Button from '../button/Button';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/SlidingPanel.scss';

const n = createNamespace('SlidingPanel');

export const EVENT_OPEN = 'slidingPanel:open';
export const EVENT_CLOSE = 'slidingPanel:close';

const DEFAULT_ANIM_TIME = 300;

const SlidingPanel = ({
    isVisible,
    onClose,
    animTime,
    children,
    i18n: {
        closePanel
    }
}) => {
    // have to trigger an event whenever the visible status changes, so we have to "remember" previous prop
    const [wasVisible, setWasVisible] = useState(null);

    const componentVariables = {
        animTime: `${animTime || DEFAULT_ANIM_TIME}ms`
    };

    useEffect(() => {
        if (wasVisible !== isVisible) {
            setWasVisible(isVisible);
        }
    }, [isVisible, wasVisible]);
    const closeButton = (
        <div {...n('closeButton').props}>
            <Button buttonType="icon" onClick={onClose}>
                <span {...n('closeButtonText').props}>{closePanel}</span>
                <Icon {...n('closeButtonIcon').props} type="close" />
            </Button>
        </div>
    );
    return (
        <div {...n('wrapper', isVisible ? 'visible' : 'hidden').withVariables(componentVariables).withTestId().withE2EId().props}>
            {children}
            {closeButton}
        </div>
    );
};

SlidingPanel.propTypes = {
    isVisible: PropTypes.bool,
    animTime: PropTypes.number,
    onClose: PropTypes.func,
    i18n: PropTypes.shape({
        closePanel: PropTypes.string
    })
};

SlidingPanel.defaultProps = {
    isVisible: false,
    animTime: DEFAULT_ANIM_TIME,
    onClose: () => null,
    i18n: {
        closePanel: 'Close panel'
    }
};

export default SlidingPanel;
