import React, { useState, useEffect, useRef } from "react";
import { actionFindUsers } from '../actions'
import {store} from '../reducers'
import { connect } from "react-redux";


const UserSearch = ({
    findedUsers,
    onSearch,
    alreadySearched = [],
    onAdd,
    open,
}) => {
    const [finded, setFinded] = useState([])
    const [input, setInput] = useState(null)

    useEffect(() => {
        let timeout
        if (input !== null) {
            timeout = setTimeout(() => {
                onSearch(input)
            }, 500)
        }
        return () => {
            clearTimeout(timeout)
        }
    }, [input])

    useEffect(() => {
        setFinded(findedUsers)
    }, [findedUsers])

    useEffect(() => {
        setInput(null)
        setFinded([])
    }, [open])

    return (
        <div className="userSearchBox">
            <div className="searchField">
                <input setInput={setInput} text={'Найти пользователя'} />
            </div>

            <div className="usersBox">
                <div className="usersList">
                    {finded.map((user) => (
                        <input
                            key={user._id}
                            user={user}
                            
                            onAction={() => onAdd(user)}
                            disabled={
                                !!alreadySearched.find(
                                    (searchedUser) =>
                                        searchedUser._id === user._id
                                )
                            }
                        />
                    ))}
                </div>
            </div>
        </div>
    )
}

const useLocalStoredState = (defaultState, localStorageKey) => {
    const json = localStorage[localStorageKey];

    try {
        defaultState = JSON.parse(json);
    } catch (e) {}

    const [state, setState] = useState(defaultState);

    localStorage.setItem(localStorageKey, JSON.stringify(state));

    return [state, setState];
};

export const Input = () => {
    const [text, setText] = useLocalStoredState(" ", "inputText");

    return <input value={text} onChange={(e) => setText(e.target.value)} />;
};

const ThemeContext = React.createContext();

export const InputDebounce = ({}) => {
    const [text, setText] = useState("");

    const timeoutRef = useRef();

    useEffect(() => {
        clearInterval(timeoutRef.current);

        if (text)
            timeoutRef.current = setTimeout(
                () => console.log(store.dispatch(actionFindUsers())),
                2000
            );
    }, [text]);

    return <input value={text} onChange={(e) => setText(e.target.value)} />;
};


export const CUserSearch = connect(
    (state) => ({ findedUsers: state.promise.findUsers?.payload || [] }),
    { onSearch: actionFindUsers }
)(InputDebounce)


