import {useEffect, useState} from "react";
import {useTranslation} from "react-i18next";

const removeDiacritics = str => {
    return str
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
}


export function SearchBar({search, defaultValue = ""}) {
    const [searchInput, setSearchInput] = useState(defaultValue);
    const {t} = useTranslation();

    const handelChange = (e) => {
        setSearchInput(e.target.value);
    }

    const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
            searchMember();
        }
    }

    const searchMember = () => {
        search(removeDiacritics(searchInput));
    }

    useEffect(() => {
        const delayDebounceFn = setTimeout(() => {
            searchMember();
        }, 750)
        return () => clearTimeout(delayDebounceFn)
    }, [searchInput])

    return <div className="mb-3">
        <div className="input-group mb-3">
            <input type="text" className="form-control" placeholder={t('rechercher...')} aria-label={t('rechercher...')}
                   aria-describedby="button-addon2" value={searchInput} onChange={handelChange} onKeyDown={handleKeyDown}/>
            <button className="btn btn-outline-secondary" type="button" id="button-addon2"
                    onClick={searchMember}>{t('rechercher')}
            </button>
        </div>
    </div>
}
