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

import CompetencesEditor from './CompetencesEditor';

import './CompetencesCellEditor.scss';

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

    const refContainer = useRef(null);

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

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

            isPopup() {
                return true;
            },

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

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

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

            <CompetencesEditor
                titre="Éditeur de compétences"
                context={props.context}
                competences={competences}
                setCompetences={setCompetences}
                maxSelectedItems={props.maxSelectedItems}
            />
        </div>
    );
});

export default CompetencesCellEditor;
