//@ts-ignore: Cannot find module '@wordpress/i18n' or its corresponding type declarations.
import { __ } from '@wordpress/i18n';
import { useState, useEffect } from '@wordpress/element'
//@ts-ignore: Cannot find module '@wordpress/components' or its corresponding type declarations.
import { PanelBody, PanelRow, __experimentalNumberControl as NumberControl, TextareaControl, Modal, Button, TextControl,Notice     } from '@wordpress/components';
import { wordpress, link, resizeCornerNE, edit, trash } from '@wordpress/icons';

import MediaGroupActions from '../../../../../../../shared/media-2d/components/MediaGroupActions';
import WpMediaUploader from '../../../../../../../shared/media-2d/components/WpMediaUploader';
import DurationNumberControl from '../../../../../../../shared/media-2d/components/DurationNumberControl';
import type { ImageGroupUrlList, ImageGroupWp, MediaGroups, VideoGroupUrl, VideoGroupWp } from '../../../../../../../shared/media-2d/types';
import type { AttributesCanvas2d } from '../../../../types';
import { DC2D } from '../../../../../../../dbg';
import BulkActionsWp from './BulkActionsWp';
import BulkActionsUrl from './BulkActionsUrl';
import ThumbnailListIds from './ThumbnailListIds'
import ThumbnailListUrls from './ThumbnailListUrls';
import FocalPointPicker from './FocalPointPicker'
import BgSize from './BgSize';
import { mediaGroupPositionAndSizeSchema } from '../../../../../../../shared/media-2d/typesZod';
import getHrefUpgrade from '../../../../../../getHrefUpgrade';

declare const wp: any; 
const { applyFilters, } = wp.hooks; 

export default function SingleGroupControls({
    attributes, 
    setAttributes, 
    index, 
    setIndex,
}:{
    attributes: AttributesCanvas2d, 
    setAttributes:any, 
    index:number, 
    setIndex:any,
}) {
    const type = attributes.mediaGroups[index]?.type;

  const hasWss = applyFilters('scrollsequence-c2d-wss-control', true) as boolean;
  const showWssNotice = hasWss && index > 2;

    return (
        <>
            <HeaderGroupSidebar attributes={attributes} setAttributes={setAttributes} index={index} setIndex={setIndex} />
            {showWssNotice && (
                <Notice status="warning" isDismissible={false} style={{marginBottom: '10px'}}>
                    <strong>Warning:</strong> You are on a free plan which limits you to 3 media groups.
                    This media group (position {index + 1}) will not be displayed on the front end.
                    <br/>
                    Please <a href={getHrefUpgrade()} target="_blank">upgrade</a> to a premium plan to remove this limit.
                </Notice>
            )}
            {type === 'wpMedia' && (
                <SingleMediaGroupWpMedia
                    attributes={attributes}
                    setAttributes={setAttributes}
                    index={index}
                    setIndex={setIndex}
                />
            )}
            {type === 'urlList' && (
                <SingleMediaGroupUrlList
                    attributes={attributes}
                    setAttributes={setAttributes}
                    index={index}
                    setIndex={setIndex}
                />
            )}
            {type === 'wpVideo' && (
                <SingleMediaGroupWpVideo
                    attributes={attributes}
                    setAttributes={setAttributes}
                    index={index}
                    setIndex={setIndex}
                />
            )}
            {type === 'urlVideo' && (
                <SingleMediaGroupUrlVideo
                    attributes={attributes}
                    setAttributes={setAttributes}
                    index={index}
                    setIndex={setIndex}
                />
            )}
            {type === 'gap' && (
                <SingleMediaGroupGap
                    attributes={attributes}
                    setAttributes={setAttributes}
                    index={index}
                    setIndex={setIndex}
                />
            )}

            
            {!['wpMedia', 'urlList', 'wpVideo', 'urlVideo', 'gap'].includes(type) && (
                <SingleMediaGroupError
                    attributes={attributes}
                    setAttributes={setAttributes}
                    index={index}
                    setIndex={setIndex}
                />
            )}
        </>
    );
}

interface PanelMediaGroup {
    attributes: AttributesCanvas2d,
    setAttributes:any
    index: number
    setIndex: any
}
function HeaderGroupSidebar({attributes, setAttributes, index, setIndex}:PanelMediaGroup){
    const { mediaGroups } = attributes
    return(
        <div 
            style={{
                display: "flex", 
                justifyContent: "space-between", 
                alignItems:"center" ,
                marginTop: "8px", 
                marginBottom: "16px", 
                minHeight: "36px"
            }}
        >
            <span 
                style={{
                    fontSize: "11px",
                    fontWeight: "500",
                    lineHeight: "1.4",
                    textTransform: "uppercase"
                }}
            >
                {`${attributes.mediaGroups[index].type}`}
            </span>
            <MediaGroupActions 
                uiVariant='dropdown'
                attributes={attributes} 
                setAttributes={setAttributes    } 
                index={index}
                setIndex={setIndex}
            />                   
        </div>   
    )
}

type Thumbnail = {
  id: number;
  url: string | null;
  file_name: string; 
}

function SingleMediaGroupWpMedia({
    attributes, 
    setAttributes, 
    index, 
    setIndex,
}:{
    attributes: AttributesCanvas2d, 
    setAttributes:any, 
    index:number, 
    setIndex:any,

}) {

    const imageGroupWp = attributes.mediaGroups[index] as ImageGroupWp
    const [thumbnails, setThumbnails] = useState<Thumbnail[]>([]);

    // Track loading state for media selection to disable UI while updating
    function handleSelectionComplete(selectedIds: number[]) {
        //console.log('0___ handleSelectionComplete (new) selectedIds:', selectedIds);
        const previousIds = imageGroupWp.images
        //console.log('1___ previousIds', previousIds);
        const mergedImagesWithDuplicates = [...previousIds, ...selectedIds];
        //console.log('2___ mergedImagesWithDuplicates', mergedImagesWithDuplicates);
        const newMediaGroups = [...attributes.mediaGroups];
        newMediaGroups[index] = {
            ...newMediaGroups[index],
            images: mergedImagesWithDuplicates
        } as ImageGroupWp;
        //console.log('3___ newMediaGroups', newMediaGroups);
        setAttributes({ mediaGroups: newMediaGroups });
    }



    useEffect(() => {
        if (!imageGroupWp.images?.length) {
            setThumbnails([]);
            return;
        }
        // Find IDs missing in thumbnails
        const imageIds = imageGroupWp.images
        

        if (imageIds.length === 0) return; // No need to fetch

        async function fetchUrlsFromRestApi(ids:any[]) {
            try { 
                //@ts-ignore: Cannot find name 'scroll_sequence_editor_data' 
                const response = await fetch(`${scroll_sequence_editor_data.wpApiSettings.root}scroll-sequence/v2/canvas2d/image-urls`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({payload: ids.map((id) => ({id, width: 100}))}),
                });
                if (!response.ok) {
                    console.error('Failed fetching image urls from REST API: ', response);
                    return [] 
                }
                const responseObj: { id: number; url: string, width:number, file_name:string }[] = await response.json();
                return responseObj
            } catch (error) {
                console.error('Error fetching image urls from REST API: ', error);
                return []; 
            }          
        }
        fetchUrlsFromRestApi(imageIds).then((newThumbs) => {
            // 1. Build a lookup map from the fetched data
            const thumbMap = new Map<number, Thumbnail>();
            newThumbs.forEach((attachment: Thumbnail) => {
                thumbMap.set(attachment.id, attachment);
            });

            // 2. Map over original imageIds, preserving order and duplicates
            setThumbnails(
                imageIds.map((id) => {
                    const thumb = thumbMap.get(id);
                    return thumb
                        ? { id: thumb.id, url: thumb.url, file_name: thumb.file_name }
                        : { id, url: null, file_name: '' }; // fallback if missing
                })
            );
        });
    }, [imageGroupWp.images]);
    return (
        <>
            
            <PanelRow>
                <div style={{ flex: 1, marginBottom: "1rem"  }} > 
                    <DurationNumberControl label="Group Duration" attributes={attributes} setAttributes={setAttributes} index={index}/>
                </div>
            </PanelRow>

            <p style={{fontSize: "11px", fontWeight: "500", lineHeight: "1.4", textTransform: "uppercase"}}>Media</p>
            <PanelRow >
                <ThumbnailListIds 
                    thumbnails={thumbnails} 
                    onRemove={(removeIdx) => {
                        // Remove by index from images array in attributes
                        const newMediaGroups = [...attributes.mediaGroups];
                        const newMediaGroup = {...newMediaGroups[index]} as ImageGroupWp;
                        newMediaGroup.images = [...newMediaGroup.images];
                        newMediaGroup.images.splice(removeIdx, 1);
                        newMediaGroups[index] = newMediaGroup;
                        setAttributes({mediaGroups: newMediaGroups});
                        // Remove thumbnail locally
                        setThumbnails(prev => prev.filter((_, idx) => idx !== removeIdx));
                    }}
                />
            </PanelRow>  

            <div style={{display: "flex", alignItems:"center", justifyContent: "space-between"}} >
                <WpMediaUploader
                    fileType='image'
                    multiple={true}
                    onCompleteSelection={(selectedIds: number[]) => {
                        handleSelectionComplete(selectedIds)
                    }}
                >
                    {(runUploader) => (
                        <Button 
                            style={{margin:"0.5rem"}} 
                            onClick={runUploader} 
                            variant="secondary"
                        >
                            {imageGroupWp.images.length > 0 ? (
                                __("Add More", 'scrollsequence')
                            ) : (
                                __("Add", 'scrollsequence')
                            ) }
                        </Button>
                    )}
                </WpMediaUploader>      
                {imageGroupWp.images.length > 0 && (
                    <BulkActionsWp
                        attributes={attributes} 
                        setAttributes={setAttributes} 
                        index={index}
                        thumbnails={thumbnails}
                        setThumbnails={setThumbnails}
                    /> 
                )}
                {imageGroupWp.images.length > 0 && (
                    <Button 
                        style={{margin:"0.5rem"}} 
                        icon={trash}
                        size="small"
                        isDestructive
                        onClick={()=>{
                            if (window.confirm("Are you sure you want to remove images from this image group?")) {
                                const newMediaGroups = [...attributes.mediaGroups]
                                const newMediaGroup = newMediaGroups[index] as ImageGroupWp
                                newMediaGroup.images = []
                                setAttributes({mediaGroups: newMediaGroups})
                            } else {
                                console.log("User cancelled the action.");
                            }
                        }}
                    />
                )}
            </div>


            <PanelRow>
                {(imageGroupWp.images && imageGroupWp.images.length > 0) && <BgSize attributes={attributes} setAttributes={setAttributes} index={index} />}
            </PanelRow>
            <PanelRow>
                {(imageGroupWp.images && imageGroupWp.images.length > 0) && <FocalPointPicker attributes={attributes} setAttributes={setAttributes} index={index}/>}
            </PanelRow>                       
        </>
    )
}

function SingleMediaGroupUrlList({
    attributes, 
    setAttributes, 
    index, 
    setIndex,
}:{
    attributes: AttributesCanvas2d, 
    setAttributes:any, 
    index:number, 
    setIndex:any,
}) {

    const mediaGroupUrlList = attributes.mediaGroups[index] as ImageGroupUrlList;

    return (
        
        <>
            
            <PanelRow>
                <div style={{ flex: 1, marginBottom: "1rem"  }} > 
                    <DurationNumberControl label="Group Duration" attributes={attributes} setAttributes={setAttributes} index={index}/>
                </div>
            </PanelRow> 


            {/* START - THIS IS ALMOST COPY-PASTE TO EMPTY-STATE and SINGLE-GROUP-CONTROLS - START */}
            <PanelRow>
                <div style={{ flex: 1  }} > 
                    <TextControl
                        __nextHasNoMarginBottom
                        __next40pxDefaultSize
                        label="URL Prefix (optional)"
                        help={__('Enter a prefix to be added to each URL: ', 'scrollsequence')}
                        placeholder="https://example.com/imgs/image"
                        value={ mediaGroupUrlList.prefix }
                        onChange={ ( value:any ) => {
                            const newMediaGroups = [...attributes.mediaGroups]
                            const newMediaGroup = newMediaGroups[index] as ImageGroupUrlList 
                            newMediaGroup.prefix = value                                    
                            setAttributes({mediaGroups: newMediaGroups})
                        }}
                    />     
                </div>                   
            </PanelRow>
            <PanelRow>
                <div style={{flex: 1 }}>
                    <TextareaControl
                        __nextHasNoMarginBottom
                        label="URL List"
                        help={__('Enter one URL per line', 'scrollsequence')}
                        value={ mediaGroupUrlList.images.join('\n') }
                        placeholder={ `0001\n0002\n0003` }
                        onChange={ ( value:any ) => {
                            
                            const newMediaGroups = [...attributes.mediaGroups]
                            const newMediaGroup = newMediaGroups[index] as ImageGroupUrlList 
                            newMediaGroup.images = value.split('\n');
                            setAttributes({mediaGroups: newMediaGroups})

                            DC2D&&console.log('value', value, attributes)
                            //setText( value ) 
                        }}
                    />     
                </div>           
            </PanelRow>             
            <PanelRow>
                <div style={{ flex: 1  }} > 
                    <TextControl
                        __nextHasNoMarginBottom
                        __next40pxDefaultSize
                        label="URL Suffix (optional)"
                        help={__('Enter a suffix to be added to each URL:', 'scrollsequence')}
                        placeholder=".jpg"
                        value={ mediaGroupUrlList.suffix }
                        onChange={ ( value:any ) => {
                            const newMediaGroups = [...attributes.mediaGroups]
                            const newMediaGroup = newMediaGroups[index] as ImageGroupUrlList 
                            newMediaGroup.suffix = value
                            setAttributes({mediaGroups: newMediaGroups});
                        }}
                    />     
                </div>                          
            </PanelRow>    
            {/* END - THIS IS ALMOST COPY-PASTE TO EMPTY-STATE and SINGLE-GROUP-CONTROLS - END */}



            {/* <PanelRow>
                <p onClick={()=>{ setIsModalOpen({mediaGroup: mediaGroupUrlList})}} >Open Image Group type:urllist</p>
            </PanelRow> */}
            <PanelRow>
                <ThumbnailListUrls 
                    //@ts-ignore: Type '{ i: number; dur?: number | undefined; }' is not assignable to type 'number'.ts(2322)
                    images={ mediaGroupUrlList.images} 
                    prefix={ mediaGroupUrlList.prefix }
                    suffix={ mediaGroupUrlList.suffix }
                />
            </PanelRow>    
            <div style={{display: "flex", alignItems:"center", justifyContent: "space-between"}} >
                {mediaGroupUrlList.images.length > 0 && (
                    <BulkActionsUrl
                        attributes={attributes} 
                        setAttributes={setAttributes} 
                        index={index}
                        // thumbnails={thumbnails}
                        // setThumbnails={setThumbnails}
                    /> 
                )}
            </div>


            <PanelRow>
                {(mediaGroupUrlList.images && mediaGroupUrlList.images.length > 0) && 
                    <BgSize attributes={attributes} setAttributes={setAttributes} index={index} />
                }
            </PanelRow>
            <PanelRow>
                {(mediaGroupUrlList.images && mediaGroupUrlList.images.length > 0) && 
                    <FocalPointPicker attributes={attributes} setAttributes={setAttributes} index={index}/>
                }
            </PanelRow>      
        </>
    )
}

function SingleMediaGroupWpVideo({
    attributes, 
    setAttributes, 
    index, 
    setIndex,
}:{
    attributes: AttributesCanvas2d, 
    setAttributes:any, 
    index:number, 
    setIndex:any,
}) {
    const videoGroup = attributes.mediaGroups[index] as VideoGroupWp
    return (
        <>
            <Notice status="warning" isDismissible={false} style={{marginBottom: "1rem"}}>
                <p>
                    WP Video groups are not implemented yet. Media will not be rendered. Please check back later.
                </p>
            </Notice>
            <PanelRow>
                <div style={{ flex: 1, marginBottom: "1rem"  }} > 
                    <DurationNumberControl label="Group Duration" attributes={attributes} setAttributes={setAttributes} index={index}/>
                </div>
            </PanelRow>

            <p style={{fontSize: "11px", fontWeight: "500", lineHeight: "1.4", textTransform: "uppercase"}}>Media</p>
            <div style={{display: "flex", alignItems:"center"}} >
                <WpMediaUploader
                    fileType='video'
                    multiple={false}
                    onCompleteSelection={(selectedIds: number[]) => {
                        //handleSelectionComplete(selectedIds)
                        alert('Video upload not implemented yet')
                    }}              
                >
                    {(runUploader) => (
                        <Button style={{margin:"0.5rem"}} onClick={runUploader} variant="secondary">
                            {videoGroup.video ? (
                                `Replace Video`
                            ) : (
                                `Select Video`
                            ) }
                        </Button>
                    )}
                </WpMediaUploader>       
                {videoGroup.video && (
                    <Button 
                        style={{margin:"0.5rem"}} 
                        icon={trash}
                        size="small"
                        isDestructive
                        onClick={()=>{
                            if (window.confirm("Are you sure you want to remove video from this video group?")) {
                                const newMediaGroups = [...attributes.mediaGroups]
                                const newMediaGroup = newMediaGroups[index] as VideoGroupWp 
                                newMediaGroup.video = undefined
                                setAttributes({mediaGroups: newMediaGroups})
                            } else {
                                console.log("User cancelled the action.");
                            }
                        }}
                    />
                )}
            </div>
            <PanelRow>
                {videoGroup.video  && <BgSize attributes={attributes} setAttributes={setAttributes} index={index} />}
            </PanelRow>
            <PanelRow>
                {videoGroup.video && <FocalPointPicker attributes={attributes} setAttributes={setAttributes} index={index}/>}
            </PanelRow>                                        
        </>
    )
}

function SingleMediaGroupUrlVideo({
    attributes, 
    setAttributes, 
    index, 
    setIndex,
}:{
    attributes: AttributesCanvas2d, 
    setAttributes:any, 
    index:number, 
    setIndex:any,

}) {
    const urlVideoGroup  = attributes.mediaGroups[index] as VideoGroupUrl;         
    return (
        <>
            <Notice status="warning" isDismissible={false} style={{marginBottom: "1rem"}}>
                <p>
                    URL Video groups are not implemented yet. Media will not be rendered. Please check back later.
                </p>
            </Notice>            
            <PanelRow>
                <div style={{ flex: 1, marginBottom: "1rem"  }} > 
                    <DurationNumberControl label="Group Duration" attributes={attributes} setAttributes={setAttributes} index={index}/>
                </div>
            </PanelRow>

            <PanelRow>
                <TextControl
                    __nextHasNoMarginBottom
                    __next40pxDefaultSize
                    label="Video URL"
                    help={__('Enter a video URL:', 'scrollsequence')}
                    placeholder="https://"
                    value={ urlVideoGroup.video }
                    onChange={ ( value:any ) => {
                        const newMediaGroups = [...attributes.mediaGroups]
                        const newMediaGroup = newMediaGroups[index] as VideoGroupUrl 
                        newMediaGroup.video = value
                        setAttributes({mediaGroups: newMediaGroups})
                    }}
                />
            </PanelRow>

            <PanelRow>
                {urlVideoGroup.video  && <BgSize attributes={attributes} setAttributes={setAttributes} index={index} />}
            </PanelRow>
            <PanelRow>
                {urlVideoGroup.video && <FocalPointPicker attributes={attributes} setAttributes={setAttributes} index={index}/>}
            </PanelRow>                                        
        </>
    )
}

function SingleMediaGroupGap({
    attributes, 
    setAttributes, 
    index, 
    setIndex,
}:{
    attributes: AttributesCanvas2d, 
    setAttributes:any, 
    index:number, 
    setIndex:any,
}) {
    return (
        <>
            
            <PanelRow>
                <div style={{ flex: 1  }} > 
                    <DurationNumberControl label="Group Duration" attributes={attributes} setAttributes={setAttributes} index={index}/>
                </div>
            </PanelRow>            
            <PanelRow>
                GAP : {index}
            </PanelRow>
        </>
    )
}

function SingleMediaGroupError({
    attributes, 
    setAttributes, 
    index, 
    setIndex,
}:{
    attributes: AttributesCanvas2d, 
    setAttributes:any, 
    index:number, 
    setIndex:any,

}) {
    return (
        <>
            
            <PanelRow>
                Error: unknown image group type
            </PanelRow>
        </>
    )
}
