import { useEffect, useLayoutEffect, useState } from 'react';

import useLocalSettingsStore from '@/stores/localSettingsStore';
import { Volume2Icon, VolumeOffIcon } from 'lucide-react';
import EditNavSidebar from './partials/edit-nav-sidebar';
import EditSidebar from './partials/edit-sidebar';
import EditorCanvas from './partials/editor-canvas';
import EditorControls from './partials/editor-controls';
import EditorHeader from './partials/editor-header';
import { calculateOptimalMaxWidth, calculateResponsiveWidth } from './utils/layout-constants';

// Hook to detect if viewport is below minimum width
const useViewportDetection = (minWidth = 320) => {
    const [isBelowMinWidth, setIsBelowMinWidth] = useState(false);

    useLayoutEffect(() => {
        setIsBelowMinWidth(window.innerWidth < minWidth);
    }, [minWidth]);

    useEffect(() => {
        const checkViewport = () => {
            setIsBelowMinWidth(window.innerWidth < minWidth);
        };

        checkViewport();
        window.addEventListener('resize', checkViewport);
        window.addEventListener('orientationchange', checkViewport);

        let resizeObserver;
        if (window.ResizeObserver) {
            resizeObserver = new ResizeObserver(checkViewport);
            resizeObserver.observe(document.body);
        }

        return () => {
            window.removeEventListener('resize', checkViewport);
            window.removeEventListener('orientationchange', checkViewport);
            if (resizeObserver) resizeObserver.disconnect();
        };
    }, [minWidth]);

    return isBelowMinWidth;
};

// Hook for responsive dimensions
const useResponsiveDimensions = () => {
    const [dimensions, setDimensions] = useState(() => ({
        maxWidth: calculateOptimalMaxWidth(),
        responsiveWidth: calculateResponsiveWidth(),
    }));

    useLayoutEffect(() => {
        const newMaxWidth = calculateOptimalMaxWidth();
        const newResponsiveWidth = calculateResponsiveWidth();
        setDimensions({
            maxWidth: newMaxWidth,
            responsiveWidth: newResponsiveWidth,
        });
    }, []);

    useEffect(() => {
        const handleResize = () => {
            const newMaxWidth = calculateOptimalMaxWidth();
            const newResponsiveWidth = calculateResponsiveWidth();
            setDimensions({
                maxWidth: newMaxWidth,
                responsiveWidth: newResponsiveWidth,
            });
        };

        window.addEventListener('resize', handleResize);
        window.addEventListener('orientationchange', handleResize);

        let resizeObserver;
        if (window.ResizeObserver) {
            resizeObserver = new ResizeObserver(handleResize);
            resizeObserver.observe(document.body);
        }

        let mutationObserver;
        if (window.MutationObserver) {
            mutationObserver = new MutationObserver(() => {
                setTimeout(handleResize, 50);
            });
            mutationObserver.observe(document.documentElement, {
                attributes: true,
                attributeFilter: ['style'],
            });
        }

        return () => {
            window.removeEventListener('resize', handleResize);
            window.removeEventListener('orientationchange', handleResize);
            if (resizeObserver) resizeObserver.disconnect();
            if (mutationObserver) mutationObserver.disconnect();
        };
    }, []);

    return dimensions;
};

const Editor = () => {
    const { getSetting } = useLocalSettingsStore();

    const [isEditNavSidebarOpen, setIsEditNavSidebarOpen] = useState(false);
    const [isEditSidebarOpen, setIsEditSidebarOpen] = useState(false);
    const [isMuted, setIsMuted] = useState(true); // Video starts muted by default
    const { maxWidth, responsiveWidth } = useResponsiveDimensions();
    const isBelowMinWidth = useViewportDetection(320);

    const handleEditNavClick = () => {
        setIsEditNavSidebarOpen(!isEditNavSidebarOpen);
    };

    const handleEditNavClose = () => {
        setIsEditNavSidebarOpen(false);
    };

    const handleEditClick = () => {
        setIsEditSidebarOpen(!isEditSidebarOpen);
    };

    const handleEditClose = () => {
        setIsEditSidebarOpen(false);
    };

    // Toggle mute functionality
    const handleToggleMute = () => {
        setIsMuted(!isMuted);
    };

    return (
        <div className="relative mx-auto flex min-h-screen flex-col space-y-2 py-4" style={{ width: `${responsiveWidth}px` }}>
            <EditSidebar isOpen={isEditSidebarOpen} onClose={handleEditClose} />
            <EditNavSidebar isOpen={isEditNavSidebarOpen} onClose={handleEditNavClose} />

            <EditorHeader
                className="mx-auto"
                style={{ width: `${responsiveWidth}px` }}
                onNavClick={handleEditNavClick}
                isNavActive={isEditNavSidebarOpen}
            />

            {isBelowMinWidth ? (
                <div className="aspect-[9/16]">
                    <div className="flex h-full flex-1 items-center justify-center rounded-lg border bg-white p-6 shadow-lg">
                        <div className="space-y-3">
                            <div>
                                <div className="relative">
                                    <video
                                        className="mx-auto"
                                        width="100"
                                        height="100%"
                                        src="https://cdn.memeaigen.com/videos/cat%20asking%20for%20food.webm"
                                        autoPlay
                                        muted={isMuted}
                                        loop
                                    />
                                </div>

                                <div className="w-full space-y-2 text-center">
                                    <div className="text-xl font-bold">{getSetting('genAlphaSlang') ? 'SHEESH' : 'YIKES'} 🥔</div>
                                    <p className="text-muted-foreground text-sm leading-relaxed">
                                        {getSetting('genAlphaSlang')
                                            ? 'Not gonna lie, using on a potato screen is giving L vibes. Desktop hits different - that experience is straight fire, bet!'
                                            : 'You seem to be using a potato-sized screen. Please continue with desktop for a more refined experience!'}
                                    </p>
                                    <div class="text-muted-foreground text-xs italic">
                                        Note: You can turn {getSetting('genAlphaSlang') ? 'off' : 'on'} gen alpha slang in Settings.
                                    </div>
                                </div>
                            </div>

                            <div className="flex w-full justify-center">
                                <button
                                    onClick={handleToggleMute}
                                    className="bg-opacity-50 hover:bg-opacity-70 mx-auto rounded-full bg-black p-2 text-white transition-opacity"
                                    title={isMuted ? 'Unmute video' : 'Mute video'}
                                >
                                    {isMuted ? <VolumeOffIcon className="h-4 w-4" /> : <Volume2Icon className="h-4 w-4" />}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            ) : (
                <>
                    <EditorCanvas maxWidth={maxWidth} />
                    <EditorControls
                        className="mx-auto"
                        style={{ width: `${responsiveWidth}px` }}
                        onEditClick={handleEditClick}
                        isEditActive={isEditSidebarOpen}
                    />
                </>
            )}
        </div>
    );
};

export default Editor;
