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

import DepartementsEditor from './DepartementsEditor';

import './DepartementsCellEditor.scss';

/**
 * Composant d'édition d'une liste de départements dans une cellule d'AG Grid.
 *
 * @component
 */ //TODO composant à refactoriser via un AbstractCellEditor (à la manière de AbstractPopinEditor)
const DepartementsCellEditor = forwardRef((props, ref) => {
    //console.log('DepartementsCellEditor', props);
    // Valeur du champ
    const [departements, setDepartements] = useState(props.value || []);

    const refContainer = useRef(null);

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

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

            isPopup() {
                return true;
            },

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

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

    return (
        <div
            className="DepartementsCellEditor"
            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>

            <DepartementsEditor
                titre="Éditeur de départements"
                context={props.context}
                departements={departements}
                setDepartements={setDepartements}
                maxSelectedItems={props.maxSelectedItems}
            />
        </div>
    );
});

export default DepartementsCellEditor;
