import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import ReactDOM from 'react-dom';
import { RiCloseCircleFill } from 'react-icons/all';

import './MarquesCellEditor.scss';

import MarquesEditor from './MarquesEditor';

/**
 * Composant d'édition d'un ensemble de marques dans une cellule d'AG Grid.
 *
 * @component
 */
//TODO composant à refactoriser via un AbstractCellEditor (à la manière de AbstractPopinEditor)
const MarquesCellEditor = forwardRef((props, ref) => {
    const [marques, setMarques] = useState(props.value || []);
    const refContainer = useRef(null);

    useEffect(() => {
        focus();
    }, []);

    useImperativeHandle(ref, () => {
        return {
            getValue() {
                return marques;
            },

            isPopup() {
                return true;
            },

            getPopupPosition() {
                return 'under';
            }
        };
    });

    const focus = () => {
        window.setTimeout(() => {
            let container = ReactDOM.findDOMNode(refContainer.current);
            if (container) {
                container.focus();
            }
        });
    };

    return (
        <div
            className="MarquesCellEditor"
            ref={refContainer}
            tabIndex={1} // important - without this the key presses wont be caught
        >
            <div
                className="ExitButton"
                onClick={() => {
                    props.api.stopEditing();
                }}
            >
                <RiCloseCircleFill />
                <span>Fermer</span>
            </div>
            <MarquesEditor
                context={props.context}
                typeDonnees={props.context.groupeType}
                marques={marques}
                setMarques={setMarques}
                titre="Éditeur de marques"
            />
        </div>
    );
});

export default MarquesCellEditor;
