const { __ } = wp.i18n;
const { useState, useEffect, useContext } = wp.element;
// const apiFetch = wp.apiFetch;
import { AppContext } from '../AppContext';
import { useSafiRequest } from "../hooks/useSafiRequest";
// import MiniMasonry from "minimasonry";
import MasonryGrid from "./MasonryGrid";

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

const blankSizes = [{
    "width": 1200,
    "height": 624,
    "name": "Default",
}, {
    "width": 1200,
    "height": 630,
    "name": "Open Graph",
}, {
    "width": 1200,
    "height": 600,
    "name": "Twitter Card",
}, {
    "width": 1200,
    "height": 1200,
    "name": "Square",
}];

const NewTemplate = ( { starterTemplates, loadTemplate, loadDemoTemplate, showWelcomeOverlay, ...props } ) => {

    const isPro = useContext( AppContext );
    const [templates, setTemplates] = useState( [] );
    const [tags, setTags] = useState( [] );
    const [selectedTag, setSelectedTag] = useState( null );
    const [clickedTemplate, setClickedTemplate] = useState( null );
    const [loading, setLoading] = useState( false );


    const {
        data: response,
        loading: loadingTemplate,
        error,
        refetch: fetchTemplate,
    } = useSafiRequest( '/safi-api/v1/template/' );

    const filteredTemplates = templates.filter( ( template ) => {
        if ( selectedTag ) {
            return template?.tags?.find( ( tag ) => tag.slug === selectedTag.slug );
        }
        return true;
    } )
    /**
     * 
     * @returns Recalculate the starter template layout
     */
    const templatesTotalHeight = ( cloudTemplates = false ) => {

        // const templatesEl = cloudTemplates ? filteredTemplates : [];
        const templatesEl = cloudTemplates ? filteredTemplates : starterTemplates;

        const thumbWidth = 280;
        const thumbGap = 12;
        const thumbRows = 3;
        const totalItems = templatesEl?.length || 0;

        //Total scaled height of all starter templates
        const scaledHeight = templatesEl.map( ( tpl ) => {
            if ( cloudTemplates ) {
                const ratio = tpl.thumbnailWidth / thumbWidth;
                return parseFloat( tpl.thumbnailHeight ) / ratio;
            }
            const ratio = tpl.template.content.canvas.width / thumbWidth;
            return parseFloat( tpl.template.content.canvas.height ) / ratio;
        } )

        //Get the highest value to add it to the calculated height
        const tallestValue = Math.max( ...scaledHeight );

        //Sum of all templates scaled heights, including the gaps
        const totalHeight = scaledHeight.reduce( ( partialSum, a ) => partialSum + a, 0 ) + thumbGap * totalItems;

        if ( cloudTemplates ) {
            return ( totalHeight / thumbRows ) + tallestValue;
        }
        return ( totalHeight / thumbRows );
    }

    useEffect( () => {
        if ( showWelcomeOverlay === true && templates.length === 0 ) {
            fetchTemplates();
            // fetchSiteLogo();
        }
    }, [showWelcomeOverlay] );

    useEffect( () => {
        if ( templates.length > 0 ) {
            //     "page": 1,
            //     "total_pages": 1,
            //     "templates": [ {
            //             "name": "Healthy food",
            //             "id": "925442c1",
            //             "last_modified": 1693293567,
            //             "group": "Healthy food",
            //             "tags": [ {
            //                 "name": "Travel",
            //                 "slug": "travel"
            //             }, {
            //                 "name": "Holiday",
            //                 "slug": "holiday"
            //             } ],
            //             "thumbnail": "https://safi.co/healthy-food.png"
            //         },
            //         {
            //             "name": "Wavy",
            //             "id": "2b82dd9b",
            //             "last_modified": 1692852328,
            //             "tags": [ {
            //                 "name": "Travel",
            //                 "slug": "travel"
            //             }, {
            //                 "name": "Holiday",
            //                 "slug": "holiday"
            //             } ],
            //             "thumbnail": "https://safi.co/healthy-food.png"
            //         },
            //         {
            //             "name": "Party",
            //             "id": "c37741e5",
            //             "last_modified": 1693469007823,
            //             "tags": [ {
            //                 "name": "Travel",
            //                 "slug": "travel"
            //             }, {
            //                 "name": "Holiday",
            //                 "slug": "holiday"
            //             } ],
            //             "thumbnail": "https://safi.co/healthy-food.png"
            //         }
            //     ]
            // }

            // Merges the tags of each templates into a single array
            const tags = Array.from(
                new Map(
                    templates
                        .filter( template => template?.tags )
                        .flatMap( template => template?.tags )
                        .map( tag => [tag.slug, tag] ) // use slug as the key
                ).values()
            );
            setTags( tags );
        }
    }, [templates] );


    const fetchTemplates = async () => {

        setLoading( true );

        // const cachedTemplates = null;
        const cachedTemplates = localStorage.getItem( "SAFI_TEMPLATES" );

        // Check the expiry dates of the cached templates
        if ( cachedTemplates ) {
            const cachedTemplatesJSON = JSON.parse( cachedTemplates );
            if ( cachedTemplatesJSON?.expires > Date.now() ) {
                setLoading( false );
                setTemplates( cachedTemplatesJSON.templates );
                return;
            }
        }

        let reqHeaders = {
            'Accept': 'application/json',
            'X-Safi-User-Id': window.SAFI?.license?.user_id || window.SAFI?.license?.trial_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 );


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

            headers: reqHeaders,
            // body: JSON.stringify( {
            //     search: search,
            //     page: searchPage,
            // } )
        }
        // fetch( rootURL + '/safi-api/v1/templates' )
        fetch( rootURL + '/safi-api/v1/templates', fetchOptions )
            .then( response => response.json() )
            .then( data => {
                // console.log( data );
                // setStarterTemplates( data );
                // setIsFetching( false );
                if ( data?.templates?.length > 0 ) {
                    setTemplates( data.templates );

                    localStorage.setItem( "SAFI_TEMPLATES", JSON.stringify( {
                        // expires: Date.now() + 1000 * 60, // 1 minute
                        expires: Date.now() + 1000 * 60 * 60 * 24, // 1 day
                        templates: data.templates
                    } ) );

                    // {

                }
            } )

            // } )
            .catch( ( e ) => {
                console.error( 'An error occured', e );
                alert( 'An error occured while fetching templates.' );
                // setIsFetching( false );
            } )
            .finally( () => {
                setLoading( false );
            } )
    };

    const selectTag = ( tag ) => {
        setSelectedTag( tag );
    }

    const requestCloudTemplate = async ( templateId ) => {
        setClickedTemplate( templateId );
        const res = await fetchTemplate( `/safi-api/v1/template/${templateId}` );
        // console.log( res?.template );

        if ( !res?.template ) {
            alert( __( 'An error occured, try again.', 'wpjoli-safi' ) );
            setClickedTemplate( null );
            return;
        }

        loadDemoTemplate( res );

        setClickedTemplate( null );
    }

    // console.log(starterTemplates);

    return (
        <div className={"safi-overlay" + ( ( showWelcomeOverlay ) ? " --showing" : "" )} style={{ background: 'linear-gradient(180deg, #272627 33%, #8d56fa2e), #272627' }}>
            <div className="template-selection flex gap-2">
                <div className="template-sidebar --safi-scroll-thin">

                    <div className="text-md font-bold">TAGS</div>
                    <ul className="template-sidebar-tags">
                        <li className={"template-tag" + ( ( selectedTag === null ) ? " --selected" : "" )} onClick={() => setSelectedTag( null )}>{__( "All", "wpjoli-safi" )}</li>
                        {
                            tags.map( ( tag ) => {
                                return (
                                    <li
                                        className={"template-tag" + ( ( selectedTag?.slug === tag.slug ) ? " --selected" : "" )}
                                        onClick={() => selectTag( tag )}
                                    >
                                        <span>{tag.name}</span>
                                    </li>
                                );
                            } )
                        }
                    </ul>
                </div>
                <div className="template-gallery --safi-scroll-thin">
                    <div className="template-picker">
                        <h3>{__( "Start from scratch", "wpjoli-safi" )}</h3>
                        <div className="flex justify-start">
                            <div className="inline-flex gap-2 ">
                                {
                                    blankSizes.map( ( size ) => {
                                        return (
                                            <div className="safi-template" >
                                                <div
                                                    className="safi-template-blank"
                                                    onClick={() => loadTemplate( size.width, size.height )}
                                                    style={{
                                                        aspectRatio: `${size.width}/${size.height}`
                                                    }}
                                                >
                                                    <span>{size.name}</span>
                                                    {/* Template dimensions */}
                                                    <div className="template-dimensions">
                                                        <span>{size.width}x{size.height}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        );
                                    } )
                                }

                            </div>
                        </div>
                    </div>

                    <div className="template-picker">
                        <h3>{__( "Free templates", "wpjoli-safi" )}</h3>
                        <div className="template-picker-wrap" style={{ height: templatesTotalHeight() }}>
                            {
                                starterTemplates.map( ( template ) => {
                                    return (
                                        <div
                                            className="safi-demo-template"
                                            data-tpl-id={template.id}
                                            onClick={() => loadDemoTemplate( starterTemplates.find( tpl => tpl.id === template.id ) )}
                                        // style={template.thumbnail ? {
                                        //     backgroundImage: "url(" + template.thumbnail + ")",
                                        // } : null}
                                        >
                                            <img src={template.thumbnail} alt="" />
                                            {/* Template dimensions */}
                                            <div className="template-dimensions">
                                                <span>{template.template.content.canvas.width}x{template.template.content.canvas.height}</span>
                                            </div>
                                        </div>
                                    );
                                } )
                            }
                        </div>
                        {/* {
                            !isPro &&
                            <div style={{ padding: 20, backgroundColor: "#ffffff10" }}>
                                <p>{__( "Unlock dozens of premium templates with Smart Auto Featured Image Pro", "wpjoli-safi" )}</p>
                                <p>
                                    <a className="safi-tb-btn safi-btn-primary" target="_blank" href="https://wpjoli.com/smart-auto-featured-image/">Get Pro Now</a>
                                </p>
                            </div>
                        } */}
                    </div>

                    {/* Cloud templates */}
                    <div className="template-picker">
                        <h3>{__( "Pro templates", "wpjoli-safi" )}</h3>

                        <MasonryGrid
                            isLoading={loading}
                            items={filteredTemplates}
                            onTemplateClick={( template ) => isPro ? requestCloudTemplate( template.id ) : alert( __( "Upgrade to Pro to use this template.", "wpjoli-safi" ) )}
                            loadingTemplate={clickedTemplate}
                        />
                        {/* <div className="template-picker-wrap" style={{ height: templatesTotalHeight( true ) }}> */}
                        {/* <div className="template-group">
                                {
                                    templates.slice( 0, 3 ).map( ( template ) => {
                                        return (
                                            <div
                                                className="safi-demo-template"
                                                data-tpl-id={template.id}
                                                onClick={() => requestCloudTemplate( template.id )}
                                            >
                                                <img src={template.thumbnail} alt="" />
                                                <div className="template-dimensions">
                                                    <span>{template.size.width}x{template.size.height}</span>
                                                </div>
                                                {loadingTemplate && clickedTemplate === template.id &&
                                                    <div className="safi-overlay --showing" style={{ top: 0 }}>
                                                        <span className="safi-loader"></span>
                                                    </div>
                                                }
                                            </div>
                                        );
                                    } )
                                }
                            </div> */}
                        {
                            // filteredTemplates.map( ( template ) => {
                            //     return (
                            //         <div
                            //             key={template.id}
                            //             className="safi-demo-template"
                            //             data-tpl-id={template.id}
                            //             onClick={() => requestCloudTemplate( template.id )}
                            //             style={{
                            //                 aspectRatio: template.size.width / template.size.height,
                            //                 backgroundColor: '#444',
                            //             }}
                            //         >
                            //             <img src={template.thumbnail} alt="" loading="lazy" />
                            //             {/* Template dimensions */}
                            //             <div className="template-dimensions">
                            //                 <span>{template.size.width}x{template.size.height}</span>
                            //             </div>
                            //             {loadingTemplate && clickedTemplate === template.id &&
                            //                 <div className="safi-overlay --showing" style={{ top: 0 }}>
                            //                     <span className="safi-loader"></span>
                            //                 </div>
                            //             }
                            //             {/* <span className="safi-loader"></span> */}
                            //         </div>
                            //     );
                            // } )
                        }
                        {/* </div> */}
                    </div>
                </div>
            </div>
        </div >
    );
}

export default NewTemplate;