import { useEffect, useLayoutEffect, useState } from 'react';
import { LAYOUT_CONSTANTS, calculateResponsiveScale } from '../utils/layout-constants';
import VideoEditor from './canvas/video-editor';

const useResponsiveCanvas = (maxWidth = 350) => {
    const [scale, setScale] = useState(() => calculateResponsiveScale(maxWidth));

    useLayoutEffect(() => {
        setScale(calculateResponsiveScale(maxWidth));
    }, [maxWidth]);

    useEffect(() => {
        const handleResize = () => {
            setScale(calculateResponsiveScale(maxWidth));
        };

        // Update immediately
        handleResize();

        // Event listeners
        window.addEventListener('resize', handleResize);
        window.addEventListener('orientationchange', handleResize);

        // ResizeObserver for more reliable detection
        let resizeObserver;
        if (window.ResizeObserver) {
            resizeObserver = new ResizeObserver(handleResize);
            resizeObserver.observe(document.body);
        }

        // MutationObserver for dev tools detection
        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();
        };
    }, [maxWidth]);

    return scale;
};

const EditorCanvas = ({ maxWidth = 350, onOpenTextSidebar }) => {
    const scale = useResponsiveCanvas(maxWidth);
    const displayWidth = LAYOUT_CONSTANTS.CANVAS_WIDTH * scale;
    const displayHeight = LAYOUT_CONSTANTS.CANVAS_HEIGHT * scale;

    const convertCoordinates = (e) => {
        const rect = e.currentTarget.getBoundingClientRect();
        return {
            x: (e.clientX - rect.left) / scale,
            y: (e.clientY - rect.top) / scale,
        };
    };

    return (
        <div className="flex w-full justify-center">
            <div
                style={{
                    width: `${displayWidth}px`,
                    height: `${displayHeight}px`,
                }}
            >
                <div
                    className="origin-top-left rounded-3xl border bg-white shadow-sm dark:bg-black"
                    style={{
                        width: `${LAYOUT_CONSTANTS.CANVAS_WIDTH}px`,
                        height: `${LAYOUT_CONSTANTS.CANVAS_HEIGHT}px`,
                        transform: `scale(${scale})`,
                    }}
                    onClick={(e) => {
                        const { x, y } = convertCoordinates(e);
                        // Handle your canvas interactions here
                        // x, y are the actual canvas coordinates (0-720, 0-1280)
                        console.log(`Canvas coordinates: x=${x}, y=${y}`);
                    }}
                >
                    <VideoEditor
                        width={LAYOUT_CONSTANTS.CANVAS_WIDTH}
                        height={LAYOUT_CONSTANTS.CANVAS_HEIGHT}
                        onOpenTextSidebar={onOpenTextSidebar}
                    />
                </div>
            </div>
        </div>
    );
};

export default EditorCanvas;
