//@ts-ignore: Cannot find module '@wordpress/i18n' or its corresponding type declarations.
import { __ } from '@wordpress/i18n';
import { useState, useEffect, Fragment, useRef } from '@wordpress/element'
//@ts-ignore:
import apiFetch from '@wordpress/api-fetch';
import { MediaGroups, ImageGroupWp } from '../types';
//@ts-ignore: Cannot find module '@wordpress/data' or its corresponding type declarations.
import { select } from '@wordpress/data';

// declare wp
declare const wp:any;

/**
 * wp.media selector and uploader. 
 * 
 * seceltedIds - array of attachment ids
 * 
 * see: https://wordpress.stackexchange.com/questions/368238/how-use-wp-media-upload-liberary-in-react-components
 * see: https://wordpress.stackexchange.com/questions/235406/how-do-i-select-an-image-from-media-library-in-my-plugin
 * 
 */

export default function WpMediaUploaderImages({
    children,

    preselectedIds, 
    fileType = 'image',
    multiple = true, // default true
    returnType = 'ids',

    onCompleteSelection,
}:{
    children: (runUploader: (event: any) => void) => React.ReactNode; // Render prop

    fileType?: 'image' | 'video'; // default image
    returnType?: 'ids' | 'full'; 
    preselectedIds?: number[]; 
    multiple?: boolean; 

    onCompleteSelection: (selectedIds:number[]) => void // <-- optional
}) {
    const onCompleteSelectionRef = useRef(onCompleteSelection);

    // Always keep the ref up to date
    useEffect(() => {
        onCompleteSelectionRef.current = onCompleteSelection;
    }, [onCompleteSelection]);

    const attachToPostId = select('core/editor').getCurrentPostId(); // TODO: make this dynamic, or use the current post id
    console.log('attachToPostId', attachToPostId)

    // Use useRef to persist the frame instance per component instance
    const frameRef = useRef<any>(null);

    const runUploader = (event:any) => {
        event.preventDefault()

        // If the media frame already exists, reopen it.
        if (frameRef.current) {
            frameRef.current.open();
            return;
        }

        // Create a new media frame
        frameRef.current = wp.media({
            title: `Select or Upload ${fileType === 'image' ? 'Images' : 'Videos'}`,
            button: {
                text: __('Select','scrollsequence'),
            },
            multiple: multiple, // Set to true to allow multiple files to be selected
            library: {
                type: fileType, // Restrict to images only
            },
            post: attachToPostId,         
        });
        // On Open (deal with pre-selected if there are any)
        frameRef.current.on('open', function() {
            const selection = frameRef.current.state().get('selection'); // get current selection
            selection.reset(); // Clear previous selection
            preselectedIds?.length && preselectedIds.forEach(function(id) {
                var attachment = wp.media.attachment(id);
                attachment.fetch();
                selection.add( attachment ? [ attachment ] : [] );
            });
        });
        // On Select
        frameRef.current.on('select', async function () {
            const attachments = frameRef.current.state().get('selection').toJSON();
            //console.log('attachments', attachments);

            const attachmentsIds = attachments.map((attachment: any) => attachment.id);
            //console.log('attachmentsIds', attachmentsIds);

    
            // NOT NEEDED NOW, USED FOR SHOW/HIDE MEDIA RELATED TO SCROLLSEQUENCE
            // Add metadata to each selected attachment
            // for (const id of attachmentsIds) {
            //     try {
            //         await apiFetch({
            //             path: `/wp/v2/media/${id}`,
            //             method: 'POST',
            //             data: {
            //                 meta: {
            //                     scroll_sequence_flag: true, // Custom flag
            //                 },
            //                 post: attachToPostId,    // Attach to a specific post ID
            //             },
            //         });
            //         console.log(`Metadata added and media attached to post ID ${attachToPostId} for attachment ID: ${id}`);
            //     } catch (error) {
            //         console.error(`Failed to add metadata or attach media to post ID ${attachToPostId} for attachment ID: ${id}`, error);
            //     }
            // }

            // Use the latest callback
            if (onCompleteSelectionRef.current) {
                if (returnType === 'ids'){
                    onCompleteSelectionRef.current(attachmentsIds);
                } else if (returnType === 'full') {
                    onCompleteSelectionRef.current(attachments);
                }
            }
        });   

        // Finally, open the modal on click
        frameRef.current.open();
    }

    return <>{children(runUploader)}</>;
}