import {isAudioVideoType, isFolder, useMounted} from "../../../includes/functions";
import {Tooltip} from "react-tooltip";

const {useRef, useEffect} = React;

export default function SearchBar({
                                      initFolders,
                                      initParentFolder,
                                      sort,
                                      filters,
                                      privateFolders,
                                      setFiles,
                                      fullTextSearch,
                                      initialSearchTerm,
                                      isSearchResults,
                                      setIsSearchResults,
                                      searchKeywordRef,
                                      notifications,
                                      isLoading,
                                      setIsLoading,

                                      keyword,
                                      setKeyword,
                                      error,
                                      setError,
                                      isActive,
                                      setIsActive,
                                      nonce,
                                      allFiles,
                                  }) {

    const searchRef = useRef();
    const timeOutRef = useRef(null);

    const searchMedia = (keyword) => {
        setIsLoading(true);
        setIsSearchResults(true);

        searchKeywordRef.current = keyword;

        let folders = initParentFolder ? [initParentFolder] : initFolders;

        wp.ajax.post('igd_search_files', {
            folders,
            sort,
            keyword: keyword,
            accountId: folders[0]?.accountId,
            isPrivate: privateFolders,
            fullTextSearch: fullTextSearch,
            filters: filters,
            nonce: nonce || igd.nonce,
        }).done((data) => {
            let {files, error} = data;

            if (!!error) {
                Swal.fire({
                    html: error,
                    icon: 'error',
                    confirmButtonText: wp.i18n.__('Ok', 'integrate-google-drive'),
                    customClass: {container: 'igd-swal'},
                });

                return;
            }

            // Search in initFolders by the keyword and merge with search results files
            const searchResults = folders.filter(file => file.name.toLowerCase().includes(keyword.toLowerCase()));
            files = [...searchResults, ...files];

            // Filter files
            files = files.filter(item => isFolder(item) || isAudioVideoType(item));

            setFiles(files);

        }).fail(error => {
            console.log(error);

            Swal.fire({
                title: wp.i18n.__('Error!', 'integrate-google-drive'),
                text: wp.i18n.__('Something went wrong! Please try again later.', 'integrate-google-drive'),
                icon: 'error',
                confirmButtonText: 'Ok',
                customClass: {container: 'igd-swal'},
            });
        }).always(() => {
            setIsLoading(false);
        });

        // Send search notification
        if (notifications && notifications.searchNotification) {
            wp.ajax.post('igd_notification', {
                files: folders,
                keyword: keyword,
                notifications,
                type: 'search',
                nonce: nonce || igd.nonce,
            });
        }

    }

    const handleSubmit = (e) => {
        e && e.preventDefault();

        setError(false);

        if (!keyword) {
            Swal.fire({
                title: wp.i18n.__('Error', 'integrate-google-drive'),
                text: wp.i18n.__('Please enter a keyword to search', 'integrate-google-drive'),
                icon: 'error',
                confirmButtonText: 'Ok',
                customClass: {container: 'igd-swal'},
            });
            setError(true);
            return;
        }

        searchMedia(keyword);
    }

    const isMounted = useMounted();

    // Handle search keyword
    useEffect(() => {
        if (!isMounted) return;
        if (!keyword) return;

        //if character length is less than 5, don't search
        if (keyword.length < 4) return;

        timeOutRef.current = setTimeout(() => {
            handleSubmit();
        }, 2000);

        return () => {
            clearTimeout(timeOutRef.current);
        }
    }, [keyword]);

    // Handle initial search
    useEffect(() => {

        searchRef.current.addEventListener('keydown', function (e) {
            if (e.key === ' ') {
                e.stopPropagation();
            }
        }, true);

        if (!initialSearchTerm) return;
        searchMedia(initialSearchTerm);
    }, []);

    return (
        <form ref={searchRef}
              className={`playlist-search ${isActive ? 'active' : ''} ${error ? 'error' : ''}`}
              onSubmit={handleSubmit}>


            {isLoading && <div className="igd-spinner"></div>}
            {isSearchResults && !isLoading &&
                <div className={`search-dismiss`}
                     onClick={() => {

                         setIsActive(!isActive);

                         setKeyword('');
                         setError(false);

                         setIsSearchResults(false);

                         setFiles(allFiles['']);
                     }}
                >
                    <svg width="14" height="14" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M1.5 1.5L10.5 10.5M1.5 10.5L10.5 1.5L1.5 10.5Z" stroke="#BABABA" strokeWidth="2"
                              strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                </div>
            }

            <input type="text"
                   placeholder={wp.i18n.__('Enter a keyword to search in the playlist', 'integrate-google-drive')}
                   value={keyword}
                   onChange={(e) => {
                       setKeyword(e.target.value);
                   }}
            />

            <div className="search-submit" onClick={() => {
                if (!isActive) {
                    setIsActive(true);
                    searchRef.current?.querySelector('input').focus();
                } else {
                    handleSubmit();
                }
            }}>

                <svg width="18" height="18" fill="currentColor" xmlns="http://www.w3.org/2000/svg"
                     viewBox="0 0 512 512">
                    <path
                        d="M508.5 468.9L387.1 347.5c-2.3-2.3-5.3-3.5-8.5-3.5h-13.2c31.5-36.5 50.6-84 50.6-136C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c52 0 99.5-19.1 136-50.6v13.2c0 3.2 1.3 6.2 3.5 8.5l121.4 121.4c4.7 4.7 12.3 4.7 17 0l22.6-22.6c4.7-4.7 4.7-12.3 0-17zM208 368c-88.4 0-160-71.6-160-160S119.6 48 208 48s160 71.6 160 160-71.6 160-160 160z"/>
                </svg>

                <Tooltip
                    id={`search`}
                    place="bottom"
                    effect="solid"
                    className="igd-tooltip"
                />
            </div>
        </form>
    )
}