import { set } from 'zod';
import { useToolsContext } from './ContextProvider'
import { useImg2ImgContext, useImg2VidContext, useVid2SsqContext } from './ContextProvider';
//import OutputsDisplayHistory from './OutputsDisplayHistory';

//import OutputsGrid from './OutputsGrid';
import OutputsD from './OutputsD'
import { ToolIds } from './types';

import { addMediaGroup } from '../../../../../shared/media-2d/addMediaGroup';
import { imageGroupUrlListDefaults, } from '../../../../../shared/media-2d/defaults';

export default function OutputsDisplay({ elementSize, attributes, setAttributes, setShow }: { elementSize: 's' | 'm' | 'l', attributes: any, setAttributes: any, setShow: React.Dispatch<React.SetStateAction<'canvas' | 'adder' | 'media-tools'>> }) {
    const { activeToolId, setActiveIo, setActiveToolId  } = useToolsContext();

    const { setCurrentModelId: setImg2ImgModelId, models: img2imgModels } = useImg2ImgContext();
    const { setCurrentModelId: setImg2VidModelId, models: img2vidModels } = useImg2VidContext();
    const { setCurrentModelId: setVid2SsqModelId, models: vid2ssqModels } = useVid2SsqContext();

    return (
        <div>
            {/* <OutputsGrid */}
            <OutputsD
                size={elementSize}
                onDownload={ (o, url) => {
                    console.log('download o:', o, 'url:', url);
                    if (url) {
                        const link = document.createElement('a');
                        link.href = url;
                        link.target = '_blank';
                        link.download = '';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }
                }}
                //onEdit={(o, url) => { /* // Not used atm. open your editor with this output/url */ console.log('edit o:', o, 'url:', url) }}
                onSendTo={(o, dest, url) => { 
                    console.log('______send to o:', o, 'dest:', dest, 'url:', url) 
                    if (dest.tool === 'img2img') {
                        // check specific model (todo)
                        const model = img2imgModels.find(model => model.id === dest.model);
                        if (!model) return alert(`Tool ${dest.tool} Model ${dest.model} not found`);
                        const setModelState = model.setModelState;
                        switch (dest.model) {
                            case 'fx':
                                setModelState( ( prev : any ) => ( {
                                    ...prev,
                                    input: {
                                        ...prev.input, // here i could load defaults for the model?
                                        image_url: url ,
                                        //prompt: o.input_object.prompt, // not really good idea, removing for now.
                                    }   
                                }) );
                                break;
                            case 'nb':
                                setModelState( ( prev : any ) => ( {
                                    ...prev,
                                    input: {
                                        ...prev.input, // here i could load defaults for the model?
                                        image_urls: url ? [url] : [],
                                        //prompt: o.input_object.prompt, // not really good idea, removing for now.
                                    }   
                                }) );
                                break;
                            default:
                                alert(`Tool ${dest.tool} Model ${dest.model} not supported yet`);
                                break;      
                        }
                        setActiveToolId(dest.tool as ToolIds);
                        setImg2ImgModelId(dest.model as any);
                    } else if (dest.tool === 'img2vid') {
                        // check specific model (todo)
                        const model = img2vidModels.find(model => model.id === dest.model);
                        if (!model) return alert(`Tool ${dest.tool} Model ${dest.model} not found`);

                        const setModelState = model.setModelState;
                        switch (dest.model) {
                            case 'hlo':
                                setModelState( ( prev : any ) => ( {
                                    ...prev,
                                    input: {
                                        ...prev.input, // here i could load defaults for the model?
                                        image_url: url,
                                        // end_image_url ?? 
                                        //prompt: o.input_object.prompt, // not really good idea, removing for now.
                                    }   
                                }) );
                                break;
                            case 'kdp':
                                setModelState( ( prev : any ) => ( {
                                    ...prev,
                                    input: {
                                        ...prev.input, // here i could load defaults for the model?
                                        image_url: url ,
                                        //prompt: o.input_object.prompt, // not really good idea, removing for now.
                                    }
                                }) );
                                break;
                            default:
                                alert(`Tool ${dest.tool} Model ${dest.model} not supported yet`);
                                break;      
                        }
                        // switch to the model and tool
                        setActiveToolId(dest.tool as ToolIds);
                        setImg2VidModelId(dest.model as any);
                    } else if ( dest.tool === 'vid2ssq' ) {
                        // check specific model (todo)
                        const model = vid2ssqModels.find(model => model.id === dest.model);
                        //alert('vid2ssq send to not implemented yet - it likely wont work as expected, saving and going outside today :-) ');
                        if (!model) return alert(`Tool ${dest.tool} Model ${dest.model} not found`);

                        const setModelState = model.setModelState;
                        switch (dest.model) {
                            case 'local':
                                setModelState( ( prev : any ) => ( {
                                    ...prev,
                                    input: {
                                        ...prev.input, // here i could load defaults for the model?
                                        video_url: url || '',
                                    }   
                                }) );
                                break;
                            default:
                                alert(`Tool ${dest.tool} Model ${dest.model} not supported yet`);
                                break;  
                        }
                        // switch to the model and tool
                        setActiveToolId(dest.tool as ToolIds);
                        setVid2SsqModelId(dest.model as any);                        
                    }

                    // switch to the model and tool
                    setActiveIo('input');
                    
                }}
                onAddToCanvas2D={(o) => {
                    console.log('Add to Canvas 2D o:', o);
                    console.log('attributes before:', attributes);

                    const newImageUrlGroup = imageGroupUrlListDefaults;
                    console.log('newImageUrlGroup before adding images:', newImageUrlGroup);

                    const { outputVars, prefix,  } = returnOutputVarsAndPrefix(o.output_urls || []);
                    newImageUrlGroup.prefix = prefix;
                    newImageUrlGroup.images = outputVars;

                    const prevMediaGroups = attributes.mediaGroups;
                    const newMediaGroups = [...prevMediaGroups, newImageUrlGroup]; // copy the array
                    console.log('newMediaGroups after adding newImageUrlGroup:', newMediaGroups);
                    setAttributes({mediaGroups: newMediaGroups})
                    setShow('canvas');
                    console.log('attributes after:', attributes);

                    // custom logic to add the output to Canvas 2D block
                }}
            />
            {/* <pre>{JSON.stringify(outputs, null, 2)}</pre> */}
        </div>
    );
}


function returnOutputVarsAndPrefix(outputUrls: string[]) {
    if (outputUrls.length === 0) {
        return { outputVars: [], prefix: '', };
    }
    // Find common prefix, it is the filename and extension part
    const firstUrl = outputUrls[0];
    const lastSlashIndex = firstUrl.lastIndexOf('/');
    // prefix = everything to the left of the last slash (or empty string if none)
    const prefix = lastSlashIndex !== -1 ? firstUrl.substring(0, lastSlashIndex+1) : '';

    // output vars are just the filenames
    const outputVars = outputUrls.map(url => {
        const lastSlashIndex = url.lastIndexOf('/');
        return lastSlashIndex !== -1 ? url.substring(lastSlashIndex + 1) : url;
    });
    return { outputVars, prefix };
}