// Import necessary libraries and components
import { __, _x } from '@wordpress/i18n';
import './editor.css';
import jQuery from 'jquery';
import { registerBlockType } from '@wordpress/blocks';
import { Button, Modal, TabPanel, TextControl } from '@wordpress/components';
import { useState } from '@wordpress/element';
import {
    useBlockProps,
    BlockControls,
    AlignmentToolbar, 
} from '@wordpress/block-editor';
import background from './img/loader-ytam.gif';


// Register a new block type for YouTube automation
registerBlockType('ytam/youtube-automate', {
    apiVersion: 3,
    title: 'Easy YouTube Automate', 
    icon: 'youtube',
    category: 'media',
    attributes: {
        alignment: {
            type: 'string',
            default: 'none',
        },
    },
    edit: ( props ) => {

        // Initialize state hooks for modal and search terms
        const { attributes, setAttributes, clientId }           = props;
        const [isModalOpen, setIsModalOpen]                     = useState(false);
        const [searchTerm, setSearchTerm]                       = useState('');
        const [resultsSearch, setResultsSearch]                 = useState('');
        const [tabIndex, setTabIndex]                           = useState(null);

        // Define translations for UI text
        const searchForVideosText   = __( 'Search for Videos', 'easy-youtube-automate' );
        const automaticSearch       = __( 'Automatic Video', 'easy-youtube-automate' );
        const closeTheWindowText    = __( 'Close the window', 'easy-youtube-automate' );
        const searchStr             = __( 'Search', 'easy-youtube-automate' );
        const useVideo              = __( 'Use this video', 'easy-youtube-automate' );
        const noApiKey              = __( 'You have to fill your YouTube API key on the', 'easy-youtube-automate' );

        // Handle alignment changes
        const onChangeAlignment = ( newAlignment ) => {
            setAttributes({
                alignment: newAlignment === undefined ? 'none' : newAlignment,
            });
        };

        
        // Handle clicking on a video thumbnail
        async function handleUseImageClick(videoID) {

            // Find the div with the loader class and change its classes
            const loaderDiv = document.querySelector('.loader-ytam');
            
            if (loaderDiv) {
                loaderDiv.classList.add('show');
                loaderDiv.classList.remove('hidden');
            }

            // Call function to insert video block into editor
            InsertVideoBlock(videoID);

        }

         // Toggle the state of the modal
        function toggleModal(shouldSearch = true, blockData = '') {

            setIsModalOpen(!isModalOpen);
        }

         // Handle changes in search input
        function handleSearchChange(value) {
            setSearchTerm(value);
        }

        function onChangeContent(newContent) {
            setContent(newContent);
        }

        // Insert video block into the editor
        function InsertVideoBlock(videoID) {

            // Insert video block if download data successful
            const { dispatch, select } = wp.data;

            const selectedBlockClientId = select('core/block-editor').getSelectedBlockClientId();
            const indexBlock = wp.data.select('core/block-editor').getBlocks().map(function(block) { 
                return block.clientId == selectedBlockClientId; 
            }).indexOf(true) + 1;

            const youtubeVideoURL = 'https://www.youtube.com/watch?v='+videoID;

            const newBlock = wp.blocks.createBlock('core/embed', {
                //id: response.data.id_media
                url: youtubeVideoURL,
            });


            // Insert the new block just after the currently selected block
            dispatch('core/block-editor').insertBlock(newBlock, indexBlock);

            // Delete the currently selected block
            dispatch('core/block-editor').removeBlock(selectedBlockClientId);
 
        }
        
        // Shuffle the array elements
        function shuffleArray(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
            return array;
        }

        // Automatically add videos based on post title
        function automaticAdd() {

            const ajaxUrl   = ytamAjax.ajax_url;
            const postId    = wp.data.select('core/editor').getCurrentPostId();
            const postTitle = wp.data.select('core/editor').getEditedPostAttribute('title');
            const params    = new URLSearchParams({
                action: 'block_searching_videos',
                search: postTitle,
                index: 1,
                id: postId,
                nonce: ytamAjax.nonce
            });

            let displayResults = '';
        
            fetch(`${ajaxUrl}?${params.toString()}`)
                .then(response => response.json())
                .then(data => {

                    let images;
                    let results;
                    let finalUrl;
                    let videoID;

                    if (data.success) {
                        
                        if (data.success && data.data && data.data.results) {

                            if (data.data.results[0].snippet.title.length > 0) {
                                //images = renderImages(data);

                                // Take the first result
                                let videoID = data.data.results[0].id.videoId;

                                InsertVideoBlock(videoID);

                            } else {
                                //images = renderNoResults();
                            }

                        } else {
                            console.error('Unexpected format:', data);
                        }

                    } else {}

                })
                .catch(error => {
                    console.error('Network Error:', error);
                });

        }
        
    
        // Handle search submissions
        function handleSearchSubmit(index, shouldSearch = true) {

            // Show loader during search results */
            let loaderSearch = document.querySelector(`.loader-searching`);
            if( loaderSearch ) {
                loaderSearch.classList.remove('hidden');
            }
            
            // Empty previous results
            let restultDiv = document.querySelector(`.results-search ul`);
            if (restultDiv) {
                restultDiv.classList.add('hidden');
            }

            const ajaxUrl   = ytamAjax.ajax_url;
            const postId    = wp.data.select('core/editor').getCurrentPostId();
            const params    = new URLSearchParams({
                action: 'block_searching_videos',
                search: searchTerm,
                index: index,
                id: postId,
                nonce: ytamAjax.nonce
            });

            let displayResults = '';
        
            fetch(`${ajaxUrl}?${params.toString()}`)
                .then(response => response.json())
                .then(data => {

                    let images;
                    let results;
                    let finalUrl;

                    if (data.success) {
                        
                        if (data.success && data.data && data.data.results) {

                            if (data.data.results[0].snippet.title.length > 0) {
                                images = renderImages(data);
                                
                            } else {
                                images = renderNoResults();
                            }

                            setResultsSearch(images);

                        } else {
                            console.error('Unexpected format:', data);
                        }

                    } else {

                        // Maybe API connecting problem
                        images = (
                            <>
                            <p>
                                {__(
                                    'No results were found for your search. There may be an API issue with your credentials. Please check your credentials on the ',
                                    'easy-youtube-automate'
                                )}
                                <a href={ytamAjax.admin_url + 'admin.php?page=youtube-automate&module=main-settings'} target='_blank'>
                                    {__('settings page', 'easy-youtube-automate')}
                                </a>.
                            </p>
                            </>
                          );                          
                        
                        setResultsSearch(images);
                    }

                    // Hiding loader after search results */
                    if( loaderSearch ) {
                        loaderSearch.classList.add('hidden');
                    }

                    // Show again images tab
                    if (restultDiv) {
                        restultDiv.classList.remove('hidden');
                    }

                })
                .catch(error => {
                    console.error('Network Error:', error);
                });

        }

        // Render no results message
        function renderNoResults() {
            return (
                <>
                    <p>{__( 'No results found for your search.', 'easy-youtube-automate' )}</p>
                </>
            );
        }

        // Render image results
        function renderImages(data) {

            let content = (
                <>
                    <ul className="media-grid">
                        {(data.data.results).map((data, id) => (
                            <li 
                                className={`attachment ytam-attachment attachment-${data.id.videoId}`}
                                tabIndex="0" 
                                role="checkbox" 
                                aria-label="Select image"
                                aria-checked="false"
                            >
                                <div className="attachment-preview js--select-attachment type-image subtype-jpeg landscape">
                                    <div className="thumbnail">
                                        <div className="centered">
                                            <img src={data.urlThumb} draggable="false" />
                                        </div>
                                        <div className="img-result">
                                            <div type="button" className="components-button is-primary"  onClick={() => handleUseImageClick(data.id.videoId)}>
                                                {useVideo}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div className="title-result">
                                    <p>{data.snippet.title}</p>
                                </div>
                                <div className="channel-result">
                                    <p>{data.snippet.channelTitle}</p>
                                </div>
                            </li>
                        ))}
                    </ul>
                </>
            );
        
            return content;
        }

        // Render the main block editor UI
        return (
            <div { ...useBlockProps() }>
                <BlockControls>
                    <AlignmentToolbar
                        value={ attributes.alignment }
                        onChange={ onChangeAlignment }
                    />
                </BlockControls>
                {ytamAjax.apikey_filled ? (
                    <div className="button-center">
                        <Button isPrimary onClick={() => setIsModalOpen(true)}>
                            {isModalOpen ? closeTheWindowText : searchForVideosText}
                        </Button>
                        <Button isPrimary onClick={() => automaticAdd()}>
                            {automaticSearch}
                        </Button>
                    </div>
                ) : ( 
                    <div className="button-center">
                        {noApiKey}
                        &nbsp; <a href={ytamAjax.admin_url + 'admin.php?page=youtube-automate&module=main-settings'} target='_blank'>
                            {__('settings page', 'easy-youtube-automate')}
                        </a>.
                    </div>
                )}
                {isModalOpen && (
                    <Modal
                        title={ 'Easy YouTube Automate' }
                        onRequestClose={(event) => {

                            setIsModalOpen(false);
                        }}
                        className="media-modal-content"
                    >

                        <TextControl
                            value={searchTerm}
                            onChange={(value) => setSearchTerm(value)}
                            onKeyPress={(e) => {
                                if (e.key === 'Enter') {
                                    handleSearchSubmit();
                                }
                            }}
                        />
                        <Button
                            isPrimary
                            onClick={handleSearchSubmit}
                        >
                            {searchStr}
                        </Button>

                        <div>
                            <div className={`results-search`}>
                                <span class={`hidden loader-searching`} style={{ backgroundImage: `url(${background})` }}></span>
                                {resultsSearch}
                            </div>
                        </div>

                    </Modal>
                )}
            </div>
        );
    },
    save: () => {
        return null;
    },
});