import React, { useEffect, useState } from 'react';
//@ts-ignore: Cannot find module '@wordpress/i18n' or its corresponding type declarations.
import { __ } from '@wordpress/i18n';
//@ts-ignore
import { Button, Modal } from '@wordpress/components';
import Grid from '@mui/material/Grid2';
import type { AttributesCanvas2d } from '../../../v2/blocks/canvas2d/types';

export default function ModalTemplates({ setIsOpen, attributes, setAttributes, setShow }: { setIsOpen: any, attributes: AttributesCanvas2d, setAttributes: any, setShow?: any }) {
    const [templates, setTemplates] = useState<any[] | null>(null);
    const [loading, setLoading] = useState(true);
    const skeletonLength = 8; // Number of skeleton items to show while loading

    // Track loaded and errored images by index
    const [loadedImages, setLoadedImages] = useState<{ [key: number]: boolean }>({});
    const [erroredImages, setErroredImages] = useState<{ [key: number]: boolean }>({});

    useEffect(() => {
        let isMounted = true;
        import(/* webpackChunkName: "templates-c2d" */ '../templates-c2d')
            .then(mod => {
                if (isMounted) {
                    setTemplates(mod.default || []);
                    setLoading(false);
                }
            })
            .catch(() => setLoading(false));
        return () => { isMounted = false; };
    }, []);

    // Skeleton placeholder for loading state
    const Skeleton = () => (
        <div
            style={{
                width: '100%',
                aspectRatio: '1 / 1',
                background: 'linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%)',
                borderRadius: '8px',
                marginBottom: '0.5rem',
                animation: 'skeleton-loading 1.2s infinite linear',
                border: '1px solid #eee',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >
            <span style={{ color: '#ccc', fontSize: '2rem' }}>{/*⏳- put a nicer icon here please :-) */}</span>
            <style>
                {`
                @keyframes skeleton-loading {
                    0% { background-position: -200px 0; }
                    100% { background-position: calc(200px + 100%) 0; }
                }
                `}
            </style>
        </div>
    );

    function handleSelectTemplate(template: any) {
        console.log('Selected template:', template, 'old mediaGroups:', attributes.mediaGroups);

        // add a new media group at the end of the array inside mediaGroups
        const newMediaGroups = [...attributes.mediaGroups];
        newMediaGroups.push(template.mediaGroup);
        setAttributes({ mediaGroups: newMediaGroups });

        setIsOpen(false);
        // close the adder if we have it
        if (setShow) {
            setShow('canvas');
        }
    }

    return (
        <Modal title="Select Template" onRequestClose={ () => setIsOpen(false) } isFullScreen>
            <Grid container spacing={{ xs: 2, md: 3 }} columns={{ xs: 4, sm: 8, md: 12 }}>
                {(loading || !templates
                    ? Array.from({ length: skeletonLength })
                    : templates
                ).map((template: any, index: number) => (
                    <Grid key={index} size={{ xs: 4, sm: 4, md: 3 }}>
                        <Button
                            variant="secondary"
                            style={{
                                width: '100%',
                                height: 'auto',
                                padding: 0,
                                border: 'none',
                                background: 'none',
                                boxShadow: 'none',
                                textAlign: 'inherit',
                                cursor: loading ? 'default' : 'pointer',
                                display: 'block'
                            }}
                            onClick={loading ? undefined : () => {
                                handleSelectTemplate(template);
                            }}
                            aria-label={__('Select template', 'scrollsequence') + ` ${template?.name || ''}`}
                            disabled={loading}
                        >
                            {loading ? (
                                <Skeleton />
                            ) : (
                                <div
                                    style={{
                                        width: '100%',
                                        aspectRatio: '1 / 1',
                                        overflow: 'hidden',
                                        borderRadius: '8px',
                                        border: '1px solid #eee',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        marginBottom: '0.5rem',
                                        background: '#fafafa',
                                        position: 'relative'
                                    }}
                                >
                                    {/* Show skeleton while image is loading */}
                                    {template.preview && !loadedImages[index] && !erroredImages[index] && <Skeleton />}
                                    {/* Show image if loaded and not errored */}
                                    {template.preview && !erroredImages[index] && (
                                        <img
                                            src={template.preview}
                                            alt={__('Template preview', 'scrollsequence') + ` ${template.name}`}
                                            style={{
                                                width: '100%',
                                                height: '100%',
                                                objectFit: 'cover',
                                                display: loadedImages[index] ? 'block' : 'none',
                                                position: 'absolute',
                                                top: 0,
                                                left: 0
                                            }}
                                            onLoad={() => setLoadedImages(prev => ({ ...prev, [index]: true }))}
                                            onError={() => {
                                                setLoadedImages(prev => ({ ...prev, [index]: true }));
                                                setErroredImages(prev => ({ ...prev, [index]: true }));
                                            }}
                                        />
                                    )}
                                    {/* Show fallback icon if errored */}
                                    {template.preview && erroredImages[index] && (
                                        <span style={{ color: '#ccc', fontSize: '2rem', position: 'absolute' }}>🖼️</span>
                                    )}
                                    {/* Show fallback icon if no preview */}
                                    {!template.preview && (
                                        <span style={{ color: '#ccc', fontSize: '2rem' }}>🖼️</span>
                                    )}
                                </div>
                            )}
                            <div style={{ textAlign: 'center', fontSize: '0.9rem', color: '#555' }}>
                                {loading ? <span style={{ color: '#ccc' }}>Loading...</span> : template?.name}
                            </div>
                        </Button>
                    </Grid>
                ))}
            </Grid>
        </Modal>
    );
}