const { useState, useEffect, useContext } = wp.element;
// import { createApi } from 'unsplash-js';
import PhotoAlbum from "react-photo-album";

// import apiFetch from '@wordpress/api-fetch';

// import { usimages } from "./images";
// import Icon from '../Icon';
import { AppContext } from "../../AppContext";
import Icon from "../Icon";


const PexelsBrowser = ( { isVisible, onSelect, onClose, canvas, ...props } ) => {
    const isPro = useContext( AppContext );
    const [isFetching, setIsFetching] = useState( false );
    const [search, setSearch] = useState( "" );
    const [searchPage, setSearchPage] = useState( 1 );
    const [searchTotalPage, setSearchTotalPage] = useState( null );
    const [searchResults, setSearchResults] = useState( [] );


    const [counter, setCounter] = useState( "Search" );

    useEffect( () => {
        counter > 0 && setTimeout( () => setCounter( counter - 1 ), 1000 );
        counter === 0 && setCounter( "Search" );
    }, [counter] ); //run this code when the value of template changes

    const rootURL = 'https://api.wpjoli.com/wp-json';

    const getStyles = ( () => {
        return {
            display: isVisible ? "flex" : "none",
        };
    } )();

    const handleImageClick = ( index ) => {
        // console.log( index );

        if ( !( index >= 0 ) ) {
            return false;
        }

        // console.log( searchResults[index] );
        const selectedImage = searchResults[index];

        if ( selectedImage ) {

            const maxWidth = canvas.width;

            onSelect( {
                src: selectedImage.urls.original,
                // src: selectedImage.urls.raw + "&q=90&w=" + ( maxWidth * 2 ).toString(),
                width: maxWidth,
                // width: selectedImage.width,
                height: Math.round( selectedImage.height * maxWidth / selectedImage.width ),
                originalHeight: selectedImage.height,
                originalWidth: selectedImage.width,
            } );

            // triggerUnsplashDownload( selectedImage.id );
        }

    };

    const handleSearchChange = ( e ) => {
        setSearchPage( 1 );
        setSearchTotalPage( null );
        setSearch( e.target.value );
    }

    const handleKeyDown = ( e ) => {
        if ( e.keyCode === 13 ) { //enter
            handleSearch();
        }
    }

    const handleSearch = () => {
        setIsFetching( true );

        let reqHeaders = {
            'Accept': 'application/json',
            'X-Safi-User-Id': window.SAFI?.license?.user_id || 0,
            'Content-Type': 'application/json',
        };

        


        const fetchOptions = {
            method: 'POST',
            // mode: "no-cors",

            headers: reqHeaders,


            //     data: {
            //         html: previewContent,
            //         options: options,
            //     },
            body: JSON.stringify( {
                search: search,
                page: searchPage,
            } )
        }

        fetch( rootURL + '/safi-api/v1/pexels/search', fetchOptions )
            .then( response => response.json() )
            .then( data => {
                setIsFetching( false );

                if ( searchPage > 1 ) {
                    setSearchResults( [...searchResults, ...data.pexels.photos] );
                }
                else {
                    setSearchResults( data.pexels.photos );
                }
                const totalPages = (data.pexels.total_results / data.pexels.per_page).toFixed( 0 );

                setSearchTotalPage( totalPages );
                if ( totalPages > searchPage ) {
                    setSearchPage( searchPage + 1 );
                }

                if ( isPro !== true ) {
                    setCounter( 10 );
                }
            } )

            // } )
            .catch( ( e ) => {
                console.error( 'An error occured', e );
                alert( 'An error occured, try again.' );
                setIsFetching( false );
            } );
    };

    // const triggerUnsplashDownload = ( photoID ) => {
    //     const fetchOptions = {
    //         method: 'POST',
    //         // mode: "no-cors",

    //         headers: {
    //             'Accept': 'application/json',
    //             'X-Safi-License-Id': window.SAFI?.license?.id || 0,
    //             'Content-Type': 'application/json',
    //         },
    //         body: JSON.stringify( {
    //             photo_id: photoID,
    //         } )
    //     }

    //     fetch( rootURL + '/safi-api/v1/unsplash/download', fetchOptions )
    //         .then( response => response.json() )
    //         .then( data => {

    //         } )

    //         // } )
    //         .catch( ( e ) => {
    //             alert( 'An error occured, try again.' );
    //         } );

    // };

    const images = ( () => {
        const formattedImages = searchResults.map( result => {
            return {
                src: result.urls.medium,
                width: result.width,
                height: result.height,
                title: result.description,
                author: result.user.name,
                author_profile: result.user.url,
            };
        } );

        // console.log( searchResults.map( result => {
        //     return result.urls.regular;
        // } ) );
        return formattedImages;
    } )();

    const isSearchDisabled = ( () => {
        return counter >= 0;
    } )();


    return (
        <div id="safi-pexels-browser" className="safi-image-browser-wrap"
            style={getStyles}
        >
            <div className="safi-image-browser">
                <div className="safi-ib-header">
                    <h3>Photos by <a href="https://www.pexels.com" target="_blank">Pexels</a></h3>
                    <div className="safi-ib-search-area">
                        <input
                            type="text"
                            name=""
                            id="safi-unsplash-search"
                            className="safi-plain"
                            placeholder="Mountains"
                            value={search}
                            onChange={handleSearchChange}
                            onKeyDown={handleKeyDown}
                            autoFocus
                            autoComplete="off"
                            disabled={isFetching || isSearchDisabled}
                        />
                        <button className="button" value="Search" onClick={handleSearch} disabled={isFetching || isSearchDisabled || !search.length} >{counter > 0 ? counter : "Search"}</button>
                    </div>
                    <div className="safi-close " onClick={onClose}>
                        <Icon icon="close" />
                    </div>
                </div>
                <div className="safi-ib-body --safi-scroll-thin">
                    {/* <Gallery images={images} /> */}


                    <div className={"safi-overlay overlay-ib" + ( isFetching ? " --showing" : "" )}>
                        <span className="safi-loader"></span>
                    </div>
                    <PhotoAlbum
                        photos={images}
                        layout="rows"
                        spacing={3}
                        targetRowHeight={150}
                        onClick={( { index } ) => {
                            handleImageClick( index );
                        }}
                        renderPhoto={( { photo, wrapperStyle, renderDefaultPhoto } ) => (
                            <div className="safi-ib-thumb" style={{ position: "relative", ...wrapperStyle }}>
                                {renderDefaultPhoto( { wrapped: true } )}
                                {photo.author && (
                                    <div className="safi-ib-thumb-author" >
                                        <a href={photo.author_profile + "?utm_source=smart-auto-featured-image&utm_medium=referral"} target="_blank">{photo.author}</a>
                                    </div>
                                )}
                            </div>
                        )}
                    />
                    {isPro !== true &&
                        <div className="safi-ib-pro-notice">
                            <ul>
                                <li>Unlimited results</li>
                                <li>Unrestricted searches*</li>
                                <li>HD + HQ image quality</li>
                            </ul>
                            <a className="button" target="_blank" href="https://wpjoli.com/smart-auto-featured-image/">Get Pro Now</a>
                            <p style={{
                                fontSize: "10px",
                                fontStyle: "italic",
                                color: "#ffffff80"
                            }}>*Free users are restricted to one search per 10 seconds to keep a smooth experience for both free and pro users.</p>
                        </div>
                    }
                    {/* Search results */}
                    {
                        isPro && searchPage < searchTotalPage &&
                        <button onClick={handleSearch}>More</button>
                    }
                </div>
            </div>
        </div>
    );
};

export default PexelsBrowser;