import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';

import '../styles/dialog.css';
import '../styles/main.css';

import { X } from 'react-feather';
import { IconButton } from './IconButton';
import { Button } from './Button';

export const Dialog = ({ content, title, removeHeader, open, close, confirm, confirmMessage, removeConfirm, appearance }) => {

    const node = useRef();

    const handleClickOutside = e => {
        // console.log("clicking anywhere");
        if (node.current.contains(e.target)) {
            // inside click
            return;
        }
        // outside click
        close()
    };

    useEffect(() => {
        if (open) {
            document.addEventListener("mousedown", handleClickOutside);
        } else {
            document.removeEventListener("mousedown", handleClickOutside);
        }

        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [open]);

    return (
        <>
            {
                open &&
                <div className='dialog-background blurred-background'>
                    <div className="dialog">
                        <div ref={node} className="dialog-wrapper">
                            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                                <IconButton onClick={close} icon={<X />} />
                            </div>
                            <div className="dialog-container">
                                {!removeHeader && <h2 style={{ marginBottom: 24 }}>{title}</h2>}
                                <div style={{ marginBottom: 24 }}>
                                    {content}
                                </div>
                                {!removeConfirm && 
                                    <>
                                        <Button onClick={close} style={{ marginRight: 8 }}>Cancel</Button>
                                        <Button onClick={confirm} intent="primary" appearance={appearance}>{confirmMessage || 'Confirm'}</Button>
                                    </>
                                }
                            </div>
                        </div>
                    </div>
                </div>
            }
        </>
    );
}

Dialog.propTypes = {
    content: PropTypes.node, 
    title: PropTypes.string, 
    removeHeader: PropTypes.bool, 
    open: PropTypes.bool, 
    close: PropTypes.func, 
    confirm: PropTypes.func, 
    confirmMessage: PropTypes.string, 
    removeConfirm: PropTypes.bool, 
    appearance: PropTypes.oneOf(['none', 'succes', 'danger', 'warning'])
}