import { nanoid } from 'nanoid';
import React, { useEffect, useRef, useState } from 'react';
import ReactDOM from 'react-dom';
import { getRefs } from '../../listes/commonAGGridFunctions';
import './PosteSureffectifEditor.scss';

/**
 * Composant d'édition d'un poste en sureffectif.
 *
 * @component
 * @param {import('../../../../jsdoc/types').ContexteAgGrid} props.context - Le contexte d'affichage de la liste
 * @param {object} props.infos - Les informations du poste à éditer, sous forme d'objet de type {departement: ..., codeFe: ..., lieu: ..., zoneDeDefense: ..., codeFeMere: ...}
 * @param {function} props.setInfos - Setter pour modifier les informations du poste
 * @param {string} props.titre - Titre éventuel
 *
 * @example
 * return (
 * <PosteSureffectifEditor />
 * )
 */
const PosteSureffectifEditor = (props) => {
    const [infos, setInfos] = useState(props.infos || { departement: '', codeFe: '',lieu: '', zoneDeDefense: '', codeFeMere: '', etr: ''});
    useEffect(() => {
        props.setInfos({
            departement  : infos.departement || null,
            codeFe       : infos.codeFe || null,
            lieu         : infos.lieu || null,
            zoneDeDefense: infos.zoneDeDefense || null,
            codeFeMere   : infos.codeFeMere || null,
            etr          : infos.etr || null,
        });
    }, [infos]);

    const refContainer = useRef(null);
    const refSelectDepartement = useRef(null);

    // Id uniques pour les champs
    const inputDepatementId = nanoid();
    const inputCodeFeId = nanoid();
    const inputLieuId = nanoid();
    const inputZoneDeDefenseId = nanoid();
    const inputCodeFeMereId = nanoid(); 
    const inputEtrId = nanoid();

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

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

            refSelectDepartement.current.focus();
        });
    };

    const refs = getRefs(props);

    const feFilles = refs?.FEs?.map((fe) => {return {'code': fe.code, 'libelle': fe.libelle}});
    const feMeres = refs?.FEs?.map((fe) => {return {'mere_code': fe.mere_code, 'mere_la': fe.mere_la}});
    const lieux = refs?.FEs?.map((fe) => fe.fe_garnison_lieu).filter(ele => {return ele != null});
    const zonesDef = refs?.FEs?.map((fe) => fe.zone_defense).filter(ele => {return ele != null});
    const setFeFilles = [...new Map(feFilles.map(item => [JSON.stringify(item), item])).values()];
    const setFeMeres = [...new Map(feMeres.map(item => [JSON.stringify(item), item])).values()];
    const setLieux = Array.from(new Set(lieux))
                          .sort((a, b) => (a || '').localeCompare(b));
    const setZonesDef = Array.from(new Set(zonesDef))
                             .sort((a, b) => (a || '').localeCompare(b));
    
    const setEtr = refs.etr?.map((fon) => {return {'id': fon.id, 'libelle':fon.libelle}})

    const compare = (a,b) => {
        const libelleA = a.libelle.toUpperCase();
        const libelleB = b.libelle.toUpperCase();
      
        let comparison = 0;
        if (libelleA > libelleB) {
          comparison = 1;
        } else if (libelleA < libelleB) {
          comparison = -1;
        }
        return comparison;
    }
      
    setEtr.sort(compare);

    return (
        <div className="PosteSureffectifEditor">
            {props.titre && <p className="titre">{props.titre}</p>}

            <form>
                <div className="field">
                    <label htmlFor={inputDepatementId}>Département</label>
                    <span>
                        <select
                            className="infos"
                            ref={refSelectDepartement}
                            id={inputDepatementId}
                            value={infos.departement || ''}
                            onChange={(event) => {
                                setInfos({ ...infos, departement: event.target.value || ''});
                            }}
                        >
                            <option>{infos.departement}</option>
                            {refs?.departements?.map((d) => (
                                <option key={d.id} value={d.code}>
                                    {d.code + ' (' + d.libelle + ')'}
                                </option>
                            ))}
                        </select>
                    </span>
                </div>

                <div className="field">
                    <label htmlFor={inputCodeFeId}>Code FE</label>
                    <span>
                        <select
                            className="infos"
                            id={inputCodeFeId}
                            value={infos.codeFe || ''}
                            onChange={(event) => {
                                setInfos({ ...infos, codeFe: event.target.value || ''});
                            }}
                        >
                            <option>{infos.codeFe}</option>
                            {setFeFilles?.map((f) => (
                                <option key={f.code} value={f.code}>
                                    {f.code + ' (' + f.libelle + ')'}
                                </option>
                            ))}
                        </select>
                    </span>
                </div>

                <div className="field">
                    <label htmlFor={inputLieuId}>Lieu</label>
                    <span>
                        <select
                            className="infos"
                            id={inputLieuId}
                            value={infos.lieu || ''}
                            onChange={(event) => {
                                setInfos({ ...infos, lieu: event.target.value || ''});
                            }}
                        >
                            <option>{infos.lieu}</option>
                            {setLieux?.map((l) => (
                                <option key={l} value={l}>
                                    {l}
                                </option>
                            ))}
                        </select>
                    </span>
                </div>

                <div className="field">
                    <label htmlFor={inputZoneDeDefenseId}>Zone de défense</label>
                    <span>
                        <select
                            className="infos"
                            id={inputZoneDeDefenseId}
                            value={infos.zoneDeDefense || ''}
                            onChange={(event) => {
                                setInfos({ ...infos, zoneDeDefense: event.target.value || ''});
                            }}
                        >
                            <option>{infos.zoneDeDefense}</option>
                            {setZonesDef?.map((z) => (
                                <option key={z} value={z}>
                                    {z}
                                </option>
                            ))}
                        </select>
                    </span>
                </div>

                <div className="field">
                    <label htmlFor={inputCodeFeMereId}>Code FE mère</label>
                    <span>
                        <select
                            className="infos"
                            id={inputCodeFeMereId}
                            value={infos.codeFeMere || ''}
                            onChange={(event) => {
                                setInfos({ ...infos, codeFeMere: event.target.value || ''});
                            }}
                        >
                            <option>{infos.codeFeMere}</option>
                            {setFeMeres?.map((f) => (
                                <option key={f.mere_code} value={f.mere_code}>
                                    {f.mere_code + ' (' + f.mere_la + ')'}
                                </option>
                            ))}
                        </select>
                    </span>
                </div>
                <div className="field">
                    <label htmlFor={inputEtrId}>ETR</label>
                    <span>
                        <select
                            className="infos"
                            id={inputEtrId}
                            value={infos.etr || ''}
                            onChange={(event) => {
                                setInfos({ ...infos, etr: event.target.value || ''});
                            }}
                        >
                            <option>{infos.etr}</option>
                            {setEtr?.map((e) => (
                                <option key={e.id} value={e.libelle}>
                                    {e.libelle}
                                </option>
                            ))}
                        </select>
                    </span>
                </div>
            </form>
        </div>
    );
};

export default PosteSureffectifEditor;
