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

import ZonesEditor from './ZonesEditor';

import './ZonesCellEditor.scss';

/**
 * Composant d'édition d'une liste de zones dans une cellule d'AG Grid.
 *
 * @component
 */
//TODO composant à refactoriser via un AbstractCellEditor (à la manière de AbstractPopinEditor)
const ZonesCellEditor = forwardRef((props, ref) => {

    // Valeur du champ
    const [zones, setZones] = useState(props.value || []);

    const refContainer = useRef(null);

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

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

            isPopup() {
                return true;
            },

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

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

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

            <ZonesEditor
                titre="Éditeur de zones"
                context={props.context}
                zones={zones}
                setZones={setZones}
                maxSelectedItems={props.maxSelectedItems}
            />
        </div>
    );
});

export default ZonesCellEditor;
