const { __ } = wp.i18n;
const { useState, useEffect, useContext, useRef, memo } = 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";
import Panel from "../panels/Panel";
import SimpleColorPicker from "./SimpleColorPicker";
// import SegmentedButtons from "./SegmentedButtons";
import TextRadioGroup from "./TextRadioGroup";
import MandatoryCheckboxGroup from "./MandatoryCheckboxGroup";
import SafiInput from "../ui/SafiInput";

const sources = [
    {
        value: 'unsplash',
        label: 'Unsplash',
        url: 'https://unsplash.com/?utm_source=smart-auto-featured-image&utm_medium=referral&utm_campaign=api-credit',
        icon: <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="#000000"><g id="SVGRepo_bgCarrier" strokeWidth="0"></g><g id="SVGRepo_tracerCarrier" strokeLinecap="round" strokeLinejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path fill="none" d="M0 0H24V24H0z"></path> <path d="M8.5 11v5h7v-5H21v10H3V11h5.5zm7-8v5h-7V3h7z"></path> </g> </g></svg>,
        mapping: {
            src: 'urls.small',
            href: 'urls.raw',
        }
    },
    {
        value: 'pexels',
        label: 'Pexels',
        url: 'https://www.pexels.com/',
        icon: <svg viewBox="0 0 24 24" fill="#000000" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" strokeWidth="0"></g><g id="SVGRepo_tracerCarrier" strokeLinecap="round" strokeLinejoin="round"></g><g id="SVGRepo_iconCarrier"> <path fillRule="evenodd" clipRule="evenodd" d="M12 5C12.7111 5 13.3875 5.14845 14 5.41604C15.7659 6.1876 17 7.94968 17 10C17 12.0503 15.7659 13.8124 14 14.584C13.3875 14.8516 12.7111 15 12 15V19H6V5H12ZM8 7V17H10V13H12L12.0032 12.9988C13.6427 13.0303 15.0746 11.6934 15.0443 9.95469L15.0375 9.56529C15.0121 8.10183 13.7882 6.94549 12.3257 7.00299L12.0203 7.00762L12 7H8Z" ></path> </g></svg>,
        mapping: {
            src: 'urls.medium',
            href: 'urls.original',
        }
    },
    // { value: 'pixabay', label: 'Pixabay' },
];

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

const ImageGalleryPanel = ( { className, source, onSelect, results, reqOptions, onImageZoom, ...props } ) => {

    const isPro = useContext( AppContext );

    // const searchResults = results[source.value]['photos'] || [];
    const [searchResults, setSearchResults] = useState( results?.[source?.value]?.photos || [] );

    const [searchPage, setSearchPage] = useState( 1 );
    const [searchTotalPage, setSearchTotalPage] = useState( results?.[source?.value]?.total_pages );

    // const [search, setSearch] = useState( "" );
    const [isFetching, setIsFetching] = useState( false );

    const imageGalleryRef = useRef( null );
    // console.log(searchPage, searchTotalPage, source, reqOptions);
    useEffect( () => {
        setSearchResults( results?.[source?.value]?.photos || [] );
        setSearchPage( 1 );
        setSearchTotalPage( results?.[source?.value]?.total_pages );

        //scroll all the way back up for the element imageGalleryRef
        imageGalleryRef.current.scrollTop = 0;

    }, [results] );

    useEffect( () => {
        if ( searchPage > searchTotalPage ) return;
        if ( searchPage > 1 ) {
            handleSearch();
        }
    }, [searchPage] );

    const handleNextPage = () => {
        if ( searchPage >= searchTotalPage ) return;
        setSearchPage( searchPage + 1 );
    }

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

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

        

        let fetchOptions = { ...reqOptions }
        fetchOptions.body = JSON.parse( fetchOptions.body );
        fetchOptions.body.page = searchPage; // set the correct page
        fetchOptions.body.sources = [source.value]; // use the correct source
        fetchOptions.body = JSON.stringify( fetchOptions.body );


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

                // console.log( data );
                if ( searchPage > 1 ) {
                    setSearchResults( [...searchResults, ...data.results?.[source?.value]?.photos] );
                }
                else {
                    setSearchResults( data.results );
                }
            } )

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

    const handleImageZoom = ( e, photo, a ) => {
        if ( photo ) {
            const url = photo.href;
            //parse URL to separate the query parameters
            const urlParts = url.split( '?' );
            const queryParams = new URLSearchParams( urlParts[1] );
            queryParams.set( 'w', 1200 );
            queryParams.set( 'q', 70 );
            const newUrl = urlParts[0] + '?' + queryParams.toString();

            onImageZoom( {
                ...photo,
                thumb: photo.src,
                large: newUrl,
                // width: photo.width,
                // height: photo.height
            } );
            return;
        }
        onImageZoom( null );
    }

    const handleImageClick = ( photo, e ) => {
        // console.log( photo, e );

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

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

        if ( photo ) {

            // const maxWidth = canvas.width;

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

            if ( source.value === 'unsplash' ) {
                triggerUnsplashDownload( photo.id );
            }
        }

    };

    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 handleImageClick = ( index, photo, event ) => {
    //     console.log( index, photo, event );

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

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

    //     if ( selectedImage ) {

    //         const maxWidth = canvas.width;

    //         onSelect( {
    //             src: selectedImage.urls.raw,
    //             // 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 );
    //     }

    // };

    function getValueByPath( obj, path ) {
        return path.split( '.' ).reduce( ( acc, key ) => acc && acc[key], obj );
    }
    // console.log( searchResults );
    const images = ( () => {
        if ( !searchResults ) {
            return [];
        }
        const formattedImages = searchResults.map( result => {
            // console.log( result );
            return {
                id: result.id,
                src: getValueByPath( result, source.mapping.src ), // thumb
                href: getValueByPath( result, source.mapping.href ), // full size
                // src: result.urls.small,
                width: result.width,
                height: result.height,
                title: result.description,
                author: result.user.name,
                author_profile: result.user.url,
                color: result.color,
                // description: result.description
            };
        } );

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

    const pageArray = new Array( parseInt( searchPage ) ).fill( 0 );
    // console.log( pageArray );


    return (
        <div className={`safi-image-gallery ${className || ''}`} >
            {/* Header */}
            <div className="safi-image-gallery-header">
                <h3>Photos by <a href={source.url} target="_blank">{source.label}</a></h3>
            </div>

            {/* Content */}
            <div ref={imageGalleryRef} className="safi-image-gallery-images --safi-scroll-thin flex flex-col gap-1">
                {
                    pageArray.map( ( item, i ) => {
                        // 30 images per page
                        const imageSubset = images.slice( ( i + 1 ) * 30 - 30, ( i + 1 ) * 30 );
                        // console.log( imageSubset );
                        return (
                            <PhotoAlbum
                                key={i}
                                photos={imageSubset}
                                layout="rows"
                                spacing={4}
                                targetRowHeight={180}
                                // onClick={( { index, photo, event } ) => {
                                //     handleImageClick( index, photo, event );
                                // }}
                                renderPhoto={( { photo, wrapperStyle, renderDefaultPhoto } ) => (
                                    <div
                                        className="safi-ib-thumb"
                                        style={{ position: "relative", ...wrapperStyle }}
                                        onClick={( e ) => handleImageZoom( e, photo, wrapperStyle )}
                                    >
                                        {renderDefaultPhoto( { wrapped: true } )}
                                        <div className="safi-ib-cta"
                                            onClick={( e ) => handleImageClick( photo, e )}
                                        >Insert</div>
                                        {photo.author && (
                                            <div
                                                className="safi-ib-thumb-author"
                                                onClick={( e ) => e.stopPropagation()}
                                                style={{ backgroundColor: 'color-mix(in srgb, ' + photo.color + ' 80%, black)' }}
                                            >
                                                <a href={photo.author_profile + "?utm_source=smart-auto-featured-image&utm_medium=referral"} target="_blank">{photo.author}</a>
                                            </div>
                                        )}
                                    </div>
                                )}
                            />
                        );
                    }
                    )
                }
                {/* Search results */}
                {
                    isPro && searchPage < searchTotalPage && !isFetching &&
                    <div className="flex flex-center py-4" onMouseEnter={handleNextPage}>
                        <button
                            className="safi-btn"
                            onClick={handleNextPage}>More</button>
                    </div>
                }
                {!isPro &&
                    <div className="flex flex-center py-4">
                        <div className="safi-ib-cta font-italic">Upgrade to Pro for more images</div>
                    </div>
                }
                {
                    isFetching &&
                    <div className="flex flex-center py-4">
                        <div className="safi-loader"></div>
                    </div>
                }
            </div>
            {/* Footer */}
        </div>
    );
};

const ImageGallery = ( { className, isVisible, selectedElementID, onSelect, onClose, ...props } ) => {
    // console.log( "ImageGallery render------" );
    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 [filterSource, setFilterSource] = useState( ['unsplash', 'pexels'] );
    const [color, setColor] = useState( null );
    const [filterOrientation, setFilterOrientation] = useState( null );

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

    const searchRef = useRef( null );

    const [thumbImgUrl, setThumbImgUrl] = useState( "" );
    const [fullImgUrl, setFullImgUrl] = useState( "" );
    const [fullImgLoaded, setFullImgLoaded] = useState( false );

    // run a search if "search" is set on mount
    useEffect( () => {
        if ( isVisible && search ) {
            handleSearch();
        }
    }, [] );

    useEffect( () => {
        const sourcesAvailable = sources.map( s => s.value );
        // console.log('sourcesAvailable', sourcesAvailable);
        const hasAnySource = sourcesAvailable.some( source => source in searchResults );
        // Check if searchResults has one of the offsets in sourcesAvailable
        if ( hasAnySource ) {
            saveSearchToSessionStorage();
        }
    }, [searchResults] );

    useEffect( () => {
        if ( isVisible ) {
            // focus and select all the searchRef
            searchRef.current.focus();
            searchRef.current.select();
        }

        const savedSearch = sessionStorage.getItem( "SAFI_GALLERY" );

        if ( savedSearch ) {
            try {
                const { search, page, sources, options, results } = JSON.parse( savedSearch );
                setSearch( search );
                setSearchPage( page );
                setFilterSource( sources );
                setColor( options.color );
                setFilterOrientation( options.orientation );
                setSearchResults( results );
            } catch ( e ) {
                sessionStorage.removeItem( "SAFI_GALLERY" );
            }
        }
    }, [isVisible] );

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


    const getStyles = ( () => {
        return {
            display: isVisible ? "flex" : "none",
        };
    } )();
    const handleSearchChange = ( e ) => {
        setSearchPage( 1 );
        setSearchTotalPage( null );
        setSearch( e.target.value );
    }

    const handleSearchKeyDown = ( e ) => {
        if ( e.keyCode === 13 ) { //enter
            handleSearch();
        }
    }
    const handleKeyDown = ( e ) => {
        // Prevents escape key from closing the window
        if ( e.keyCode === 27 ) {
            e.preventDefault();
            e.stopPropagation();

            // Close the zoom preview
            closeZoomPreview();
            return false;
        }
    }

    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,
            sources: filterSource,
            options: {
                color: color,
                orientation: filterOrientation
            },
        } )
    };

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


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

                // console.log( data );
                if ( searchPage > 1 ) {
                    setSearchResults( [...searchResults, ...data.results] );
                }
                else {
                    setSearchResults( data.results );
                }

                // Save the last search so that it's available on the next open
                // saveSearchToSessionStorage();
                // const totalPages = data.unsplash.total_pages;    

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

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

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


    const handleColorChange = ( color ) => {
        setColor( color );
    }

    const handleSourceChange = ( source ) => {
        setFilterSource( source );
    }

    const handleOrientationChange = ( orientation ) => {
        setFilterOrientation( orientation );
    }

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

    const handleSelect = ( photo ) => {
        const maxWidth = 1200;
        const selectedPhoto = {
            ...photo,
            width: maxWidth,
            height: Math.round( photo.originalHeight * maxWidth / photo.originalWidth ),
        };

        saveSearchToSessionStorage();
        onSelect( selectedPhoto );
    }

    // console.log( searchResults );
    // check if searchResults has the keys corresponding to filterSources
    const hasResults = ( () => {
        if ( !filterSource || !searchResults ) {
            return false;
        }

        for ( let i = 0; i < filterSource.length; i++ ) {
            if ( !searchResults[filterSource[i]] ) {
                return false;
            }
        }
        return true;
    } );

    const handleImageZoom = ( data ) => {
        // setFullImgUrl( url );
        setThumbImgUrl( data.thumb );
        setFullImgLoaded( false );
        setFullImgUrl( data );
    };

    const closeZoomPreview = () => {
        setFullImgLoaded( false );
        setFullImgUrl( "" );
    }

    // const fullImgStyles = (() => {
    //     if ( !fullImgUrl ) {
    //         return null;
    //     }
    //     const styles = {
    //         backgroundImage: `url(${fullImgUrl})`,
    //     };
    //     return styles;
    // })();

    const handleClose = () => {
        onClose();
    };

    const saveSearchToSessionStorage = () => {
        // Save the last search so that it's available on the next open
        sessionStorage.setItem( "SAFI_GALLERY", JSON.stringify( {
            search: search,
            page: searchPage,
            sources: filterSource,
            options: {
                color: color,
                orientation: filterOrientation
            },
            results: searchResults
        } ) );
    }


    // console.log( fullImgUrl );
    return (
        <div className="safi-cover-bg" style={getStyles}>
            <div
                id="safi-image-gallery"
                className={`safi-image-gallery-wrap ${className}`}
                tabIndex={0}
                onKeyDown={handleKeyDown}
            >
                <div className={"safi-overlay overlay-ib" + ( isFetching ? " --showing" : "" )}>
                    <span className="safi-loader"></span>
                </div>
                {/* Container */}
                <div className="safi-image-gallery-container flex">

                    {/* Sidebar */}
                    <div className="safi-image-gallery-sidebar safi-sidebar">
                        <Panel header={true} name="Search" isOpen={true}>
                            <div className="py-2">
                                {/* Search */}
                                <div className="safi-image-gallery-search flex flex-col gap-2">
                                    {/* <input
                                type="text"
                                placeholder="Search..."
                                value={search}
                                onChange={handleSearchChange}
                                onKeyDown={handleKeyDown}
                            /> */}
                                    <SafiInput
                                        ref={searchRef}
                                        type="text"
                                        className="w-full"
                                        placeholder="Search..."
                                        value={search}
                                        onChange={handleSearchChange}
                                        onKeyDown={handleSearchKeyDown}
                                        autoFocus
                                        disabled={isSearchDisabled}
                                    />
                                </div>
                            </div>
                        </Panel>
                        <Panel header={true} name="Sources" isOpen={true}>
                            <div className="py-2">
                                {/* Unsplash */}
                                <div className="safi-image-gallery-source flex gap-2">
                                    <MandatoryCheckboxGroup
                                        options={sources}
                                        selectedValues={filterSource}
                                        onChange={handleSourceChange}
                                    />
                                </div>
                            </div>
                        </Panel>
                        {/* Filters */}
                        {/* Color */}
                        <Panel header={true} name="Color" isOpen={true} disabled={isPro === false}>
                            <div className="py-2">
                                <SimpleColorPicker color={color} onColorChange={handleColorChange} />
                            </div>
                        </Panel>

                        {/* Orientation */}
                        <Panel header={true} name="Orientation" isOpen={true} disabled={isPro === false}>
                            <div className="py-2">
                                <div className="safi-image-gallery-orientation flex gap-2">
                                    <TextRadioGroup
                                        options={[
                                            // { value: 'all', label: 'All' },
                                            { value: 'landscape', label: 'Landscape' },
                                            { value: 'portrait', label: 'Portrait' },
                                            { value: 'square', label: 'Square' },
                                        ]}
                                        value={filterOrientation}
                                        onChange={handleOrientationChange}
                                    />

                                </div>
                            </div>
                        </Panel>
                        <div className="flex justify-center py-4">
                            <button
                                className="safi-tb-btn safi-btn-primary safi-btn-md w-1/2"
                                onClick={handleSearch}
                                disabled={isFetching || isSearchDisabled || !search.length}
                            >{counter > 0 ? counter : "Search"}</button>
                        </div>

                        {/* Language (locale) */}
                    </div>

                    {/* Galleries*/}
                    <div className="safi-image-galleries flex-1 flex-col">
                        <div className="flex gap-1 w-full" style={{ overflowY: "auto" }}>
                            {/* Gallery */}
                            {filterSource && filterSource.map( ( source ) =>
                            ( <ImageGalleryPanel
                                key={source}
                                source={sources.find( s => s.value === source )}
                                results={searchResults}
                                reqOptions={fetchOptions}
                                onSelect={handleSelect}
                                onImageZoom={handleImageZoom}
                            /> )
                            )}
                            {!hasResults() && !isFetching &&
                                <div className="flex flex-col justify-center items-center" style={{ inset: 0, position: "absolute", background: "#444" }}>
                                    <div>
                                        <p className="text-lg">{__( 'Search images using the search bar.', 'wpjoli-safi' )}</p>
                                        <p className="text-lg">{__( 'Refine your search with the filters.', 'wpjoli-safi' )}</p>
                                    </div>
                                </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 5 seconds to keep a smooth experience for both free and pro users.</p>
                            </div>
                        }
                    </div>

                    <div
                        id="safi-image-zoom"
                        className={`safi-image-galleries flex-1 items-center justify-center ${fullImgUrl === "" ? "" : "--show"}`}
                        onClick={() => { closeZoomPreview() }}
                        style={{
                            backgroundImage: `url(${thumbImgUrl})`,
                            // backgroundSize: "contain",
                            backgroundSize: "1200px auto",
                            backgroundPosition: "center",
                            backgroundRepeat: "no-repeat"
                        }}
                    >
                        <div className="relative w-full h-full flex items-center justify-center">
                            {fullImgLoaded === false && fullImgUrl !== "" &&
                                <div style={{ position: "absolute", left: "50%", top: "50%", transform: "translate(-50%, -50%)", width: "60px", height: "60px" }}>
                                    <div className="safi-loader"></div>
                                </div>
                            }
                            <img src={fullImgUrl.large} alt="" onLoad={() => setFullImgLoaded( true )} />
                        </div>
                        {/* description */}
                        <div className="safi-image-zoom--description absolute py-4 px-4" style={{ bottom: 0, left: 0, right: 0, background: "linear-gradient(0deg, rgba(0,0,0,1) 0%, rgba(0,0,0,0) 100%)" }}>
                            <div className="safi-image-zoom--description--title">{fullImgUrl?.title}</div>
                            <div className="safi-image-zoom--description--author">
                                <a className="safi-link"
                                    onClick={e => e.stopPropagation()}
                                    href={fullImgUrl?.author_profile}
                                    target="_blank"
                                    rel="noopener noreferrer">{fullImgUrl?.author}</a>
                            </div>
                        </div>
                    </div>

                    {/* <div className="safi-close " onClick={handleClose}>
                        <Icon icon="close" />
                    </div> */}
                    <div className="close-btn flex-center" onClick={handleClose} style={{
                        top: '0',
                        // right: '10px',
                        // transform: 'translateY(-50%)',
                    }}>
                        <div className="close-symbol"></div>
                    </div>
                </div>
            </div>
        </div>
    );
};

// Only re-render if props actually changed
export default memo( ImageGallery, ( prevProps, nextProps ) => {
    // Only re-render if these props change
    return (
        prevProps.isVisible === nextProps.isVisible
    );
} );

// export default ImageGallery;

// Optional helper to shallow compare objects
