import { useMemo } from '@wordpress/element';
import useEditorStore from '../store/useEditorStore';
import LoginFormBlock from '../blocks/LoginFormBlock';
import LogoBlock from '../blocks/LogoBlock';
import HeadingBlock from '../blocks/HeadingBlock';
import TextBlock from '../blocks/TextBlock';
import DividerBlock from '../blocks/DividerBlock';

import CustomHtmlBlock from '../blocks/CustomHtmlBlock';

function getYouTubeId(url) {
    if (!url) return null;
    const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    const match = url.match(regExp);
    return (match && match[2].length === 11) ? match[2] : null;
}

function LiveVideoBackground({ ps }) {
    if (ps.backgroundType !== 'video') return null;

    const source = ps.videoSource || 'youtube';
    const ytId = getYouTubeId(ps.videoYoutubeUrl);
    const hasOverlay = ps.overlayEnabled;
    const overlayColor = ps.overlayColor || '#000000';
    const overlayOpacity = ps.overlayOpacity ?? 0.4;
    const objectFit = ps.videoObjectFit || 'cover';

    const wrapperStyle = {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        overflow: 'hidden',
        zIndex: 0,
        pointerEvents: 'none',
        borderRadius: 'inherit'
    };

    const mediaStyle = {
        width: '100%',
        height: '100%',
        objectFit: objectFit,
        border: 'none',
        display: 'block'
    };

    const overlayStyle = {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        backgroundColor: overlayColor,
        opacity: overlayOpacity
    };

    return (
        <div style={wrapperStyle}>
            {source === 'youtube' && ytId && (
                <iframe
                    src={`https://www.youtube.com/embed/${ytId}?autoplay=1&mute=1&loop=1&controls=0&playsinline=1&playlist=${ytId}`}
                    style={mediaStyle}
                    allow="autoplay"
                />
            )}
            {source === 'upload' && ps.videoUploadUrl && (
                <video
                    src={ps.videoUploadUrl}
                    style={mediaStyle}
                    autoPlay muted loop playsInline
                />
            )}
            {hasOverlay && <div style={overlayStyle} />}
        </div>
    );
}

export default function Canvas() {
    const editingTemplate = useEditorStore((s) => s.editingTemplate);
    const selectedBlockId = useEditorStore((s) => s.selectedBlockId);
    const devicePreview = useEditorStore((s) => s.devicePreview);
    const setSelectedBlockId = useEditorStore((s) => s.setSelectedBlockId);
    const removeBlock = useEditorStore((s) => s.removeBlock);
    const duplicateBlock = useEditorStore((s) => s.duplicateBlock);
    const moveBlock = useEditorStore((s) => s.moveBlock);
    const switchBlockPanel = useEditorStore((s) => s.switchBlockPanel);

    const isAdvanced = editingTemplate?.type === 'advanced';

    const blocks = useMemo(() => {
        if (!editingTemplate?.jsonData?.blocks) return [];
        return [...editingTemplate.jsonData.blocks].sort((a, b) => a.order - b.order);
    }, [editingTemplate]);

    const pageSettings = editingTemplate?.jsonData?.pageSettings || {};
    const isSplit = pageSettings.layoutType === 'split_left' || pageSettings.layoutType === 'split_right';

    // For split mode: use panel property, fallback to type-based logic for old blocks.
    const getBlockPanel = (block) => {
        if (block.panel) return block.panel;
        return block.type === 'loginForm' ? 'form' : 'branding';
    };

    const brandingBlocks = useMemo(() => blocks.filter((b) => getBlockPanel(b) === 'branding'), [blocks]);
    const formBlocks = useMemo(() => blocks.filter((b) => getBlockPanel(b) === 'form'), [blocks]);

    const backgroundStyle = useMemo(() => {
        const s = {};
        if (isSplit) {
            s.display = 'flex';
            s.flexDirection = 'row';
            s.alignItems = 'stretch';
            s.minHeight = '100%';
            s.padding = '0';
            return s;
        }
        switch (pageSettings.backgroundType) {
            case 'gradient':
                s.background = `linear-gradient(${pageSettings.backgroundGradient?.angle || 135}deg, ${pageSettings.backgroundGradient?.color1 || '#667eea'}, ${pageSettings.backgroundGradient?.color2 || '#764ba2'})`;
                break;
            case 'image':
                if (pageSettings.backgroundImage) {
                    s.backgroundImage = `url(${pageSettings.backgroundImage})`;
                    s.backgroundPosition = pageSettings.backgroundPosition || 'center';
                    s.backgroundSize = pageSettings.backgroundSize || 'cover';
                    s.backgroundRepeat = 'no-repeat';
                }
                break;
            case 'animated-gradient': {
                const ag = pageSettings.animatedGradient || {};
                const colors = ag.colors || ['#667eea', '#764ba2'];
                const loopColors = [...colors, colors[0]];
                const angle = ag.angle || 135;
                const speed = ag.speed || 8;
                s.background = `linear-gradient(${angle}deg, ${loopColors.join(', ')})`;
                s.backgroundSize = '300% 300%';
                s.animation = `lpcd-gradient-shift ${speed}s ease infinite`;
                break;
            }
            case 'video':
                s.background = '#0a0a0a';
                if (pageSettings.videoFallbackImage) {
                    s.backgroundImage = `url(${pageSettings.videoFallbackImage})`;
                    s.backgroundSize = 'cover';
                    s.backgroundPosition = 'center';
                }
                break;
            default:
                s.background = pageSettings.backgroundColor || '#f0f0f1';
        }
        return s;
    }, [pageSettings, isSplit]);

    // Branding panel style.
    const brandingPanelStyle = useMemo(() => {
        if (!isSplit) return {};
        const bp = pageSettings.brandingPanel || {};
        const s = {
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: bp.verticalAlign || 'center',
            alignItems: 'center',
            padding: '2rem',
            color: bp.textColor || '#ffffff',
            textAlign: 'center',
            boxSizing: 'border-box',
            order: pageSettings.layoutType === 'split_left' ? 1 : 2,
            overflow: 'hidden',
            position: 'relative',
        };
        if (bp.backgroundType === 'image' && bp.backgroundImage) {
            s.backgroundImage = `url(${bp.backgroundImage})`;
            s.backgroundSize = bp.backgroundSize || 'cover';
            s.backgroundPosition = bp.backgroundPosition || 'center';
            s.backgroundRepeat = 'no-repeat';
        } else if (bp.backgroundType === 'gradient') {
            s.background = `linear-gradient(${bp.gradientAngle || 135}deg, ${bp.gradientColor1 || '#1a1a2e'}, ${bp.gradientColor2 || '#16213e'})`;
        } else {
            s.background = bp.backgroundColor || '#1a1a2e';
        }
        return s;
    }, [pageSettings, isSplit]);

    // Form panel style.
    const formPanelStyle = useMemo(() => {
        if (!isSplit) return {};
        const formWidth = pageSettings.splitFormWidth || 40;
        return {
            width: `${formWidth}%`,
            minWidth: `${formWidth}%`,
            maxWidth: `${formWidth}%`,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: pageSettings.splitAlignment || 'center',
            alignItems: 'center',
            padding: '1.5rem',
            boxSizing: 'border-box',
            order: pageSettings.layoutType === 'split_left' ? 2 : 1,
            background: pageSettings.backgroundColor || '#f5f0eb',
            overflow: 'hidden',
        };
    }, [pageSettings, isSplit]);

    const deviceWidths = {
        desktop: '100%',
        tablet: '768px',
        mobile: '375px',
    };

    const renderBlockContent = (block) => {
        const isSelected = selectedBlockId === block.id;
        const props = {
            key: block.id,
            block,
            isSelected,
            onSelect: () => setSelectedBlockId(block.id),
        };

        switch (block.type) {
            case 'loginForm':
                return <LoginFormBlock {...props} />;
            case 'logo':
                return <LogoBlock {...props} />;
            case 'heading':
                return <HeadingBlock {...props} />;
            case 'text':
                return <TextBlock {...props} />;
            case 'divider':
                return <DividerBlock {...props} />;

            case 'customHtml':
                return <CustomHtmlBlock {...props} />;
            default:
                return null;
        }
    };

    const renderBlock = (block) => {
        const isSelected = selectedBlockId === block.id;
        const content = renderBlockContent(block);
        if (!content) return null;

        const currentPanel = getBlockPanel(block);
        const otherPanelLabel = currentPanel === 'form' ? 'Branding' : 'Form';
        const switchIcon = currentPanel === 'form'
            ? (pageSettings.layoutType === 'split_left' ? 'dashicons-arrow-left-alt' : 'dashicons-arrow-right-alt')
            : (pageSettings.layoutType === 'split_left' ? 'dashicons-arrow-right-alt' : 'dashicons-arrow-left-alt');

        return (
            <div
                key={block.id}
                className={`lpcd-canvas-block ${isSelected ? 'selected' : ''}`}
                onClick={(e) => {
                    e.stopPropagation();
                    setSelectedBlockId(block.id);
                }}
            >
                {isSelected && !isAdvanced && (
                    <div className="lpcd-block-toolbar">
                        {isSplit && (
                            <button
                                className="lpcd-block-action lpcd-switch-panel-btn"
                                onClick={(e) => { e.stopPropagation(); switchBlockPanel(block.id); }}
                                title={`Move to ${otherPanelLabel} Panel`}
                            >
                                <span className={`dashicons ${switchIcon}`} />
                            </button>
                        )}
                        <button
                            className="lpcd-block-action"
                            onClick={(e) => { e.stopPropagation(); moveBlock(block.id, 'up'); }}
                            title="Move Up"
                        >
                            <span className="dashicons dashicons-arrow-up-alt" />
                        </button>
                        <button
                            className="lpcd-block-action"
                            onClick={(e) => { e.stopPropagation(); moveBlock(block.id, 'down'); }}
                            title="Move Down"
                        >
                            <span className="dashicons dashicons-arrow-down-alt" />
                        </button>
                        <button
                            className="lpcd-block-action"
                            onClick={(e) => { e.stopPropagation(); duplicateBlock(block.id); }}
                            title="Duplicate"
                        >
                            <span className="dashicons dashicons-admin-page" />
                        </button>
                        <button
                            className="lpcd-block-action delete"
                            onClick={(e) => { e.stopPropagation(); removeBlock(block.id); }}
                            title="Delete"
                        >
                            <span className="dashicons dashicons-trash" />
                        </button>
                    </div>
                )}
                {content}
            </div>
        );
    };

    const editorCss = useMemo(() => {
        if (!pageSettings.customCss) return '';
        // Replace body.login and other common prefixes with the canvas wrapper so editor styles apply correctly
        return pageSettings.customCss
            .replace(/body\.login/g, '.lpcd-canvas-wrapper .lpcd-canvas')
            .replace(/\.login/g, '.lpcd-canvas-wrapper .lpcd-canvas')
            .replace(/#loginform(?![a-zA-Z0-9_-])/g, '.lpcd-block-loginform')
            .replace(/#login(?![a-zA-Z0-9_-])/g, '.lpcd-canvas-inner');
    }, [pageSettings.customCss]);

    // Split layout: two-panel view.
    if (isSplit) {
        return (
            <div className="lpcd-canvas-wrapper">
                <style>{editorCss}</style>
                <div
                    className="lpcd-canvas lpcd-canvas-split"
                    style={{ ...backgroundStyle, maxWidth: deviceWidths[devicePreview], position: 'relative' }}
                    onClick={() => setSelectedBlockId(null)}
                >
                    <LiveVideoBackground ps={pageSettings} />
                    {/* Branding Panel */}
                    <div className="lpcd-canvas-branding" style={brandingPanelStyle}>
                        <div className="lpcd-panel-label">Branding Panel</div>
                        <div className="lpcd-branding-content">
                            {brandingBlocks.length === 0 && (
                                <div className="lpcd-panel-empty">
                                    <span className="dashicons dashicons-plus-alt2" />
                                    <p>Add blocks here</p>
                                </div>
                            )}
                            {brandingBlocks.map(renderBlock)}
                        </div>
                    </div>

                    {/* Form Panel */}
                    <div className="lpcd-canvas-form-panel" style={formPanelStyle}>
                        <div id="login" style={{ width: '100%' }}>
                            <div className="lpcd-panel-label">Form Panel</div>
                            {formBlocks.length === 0 && (
                                <div className="lpcd-panel-empty">
                                    <span className="dashicons dashicons-plus-alt2" />
                                    <p>Add Login Form here</p>
                                </div>
                            )}
                            {formBlocks.map(renderBlock)}
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    // Default centered layout.
    return (
        <div className="lpcd-canvas-wrapper">
            <style>{editorCss}</style>
            <div
                className="lpcd-canvas"
                style={{ ...backgroundStyle, maxWidth: deviceWidths[devicePreview], position: 'relative' }}
                onClick={() => setSelectedBlockId(null)}
            >
                <LiveVideoBackground ps={pageSettings} />
                <div id="login" className="lpcd-canvas-inner" style={{ position: 'relative', zIndex: 10 }}>
                    {blocks.map(renderBlock)}
                </div>
            </div>
        </div>
    );
}
