import React, {FC, useCallback, useEffect} from "react";
import {createPortal} from "react-dom";
import {AnimatePresence, motion} from "motion/react";
import {useAtomValue, useSetAtom} from "jotai";
import {HoveredTestableCompositeIDAtom, OverlayOpenCompositeAtom} from "./atoms";
import {TestableComposite, InsideOverlayContext} from "./TestableComposite";
import {colors} from "./Colors";
import {TestableCompositeRemoveButton} from "./TestableCompositeRemoveButton";

const SPRING = {type: 'spring', stiffness: 380, damping: 32, mass: 0.8} as const;
const BACKDROP_TRANSITION = {duration: 0.28, ease: [0.22, 1, 0.36, 1]} as const;

export const TestableCompositeOverlay: FC = () => {
    const overlayState = useAtomValue(OverlayOpenCompositeAtom);
    const setOverlayState = useSetAtom(OverlayOpenCompositeAtom);
    const setHoveredTestableCompositeID = useSetAtom(HoveredTestableCompositeIDAtom);

    const close = useCallback(() => {
        setOverlayState(null);
        setHoveredTestableCompositeID(null);
    }, [setOverlayState, setHoveredTestableCompositeID]);

    useEffect(() => {
        if (!overlayState) return;

        const onKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape') {
                close();
            }
        };

        document.addEventListener('keydown', onKeyDown);
        return () => document.removeEventListener('keydown', onKeyDown);
    }, [overlayState, close]);

    const viewportCenterX = typeof window !== 'undefined' ? window.innerWidth / 2 : 0;
    const viewportCenterY = typeof window !== 'undefined' ? window.innerHeight / 2 : 0;

    const sourceCenter = overlayState ? {
        x: overlayState.rect.left + overlayState.rect.width / 2,
        y: overlayState.rect.top + overlayState.rect.height / 2,
    } : {x: 0, y: 0};

    const offsetX = sourceCenter.x - viewportCenterX;
    const offsetY = sourceCenter.y - viewportCenterY;

    return createPortal(
        <AnimatePresence>
            {overlayState && (
                <motion.div
                    key="composite-overlay"
                    className="fixed inset-0 z-[999998]"
                    initial={false}
                >
                    {/* Backdrop */}
                    <motion.div
                        className="absolute inset-0"
                        style={{backgroundColor: 'rgba(0,0,0,0.22)', backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)'}}
                        initial={{opacity: 0}}
                        animate={{opacity: 1}}
                        exit={{opacity: 0}}
                        transition={BACKDROP_TRANSITION}
                        onClick={close}
                    />

                    {/* Scrollable overlay that keeps the card centered when it fits */}
                    <div className="absolute inset-0 overflow-y-auto overflow-x-hidden" onClick={close}>
                        <div className="min-h-full flex flex-col items-center p-4 pt-10 pb-8 pointer-events-none">
                        <motion.div
                            className="pointer-events-auto relative my-auto"
                            style={{maxWidth: '95vw'}}
                            initial={{
                                x: offsetX,
                                y: offsetY,
                                scale: 0.45,
                                opacity: 0,
                                borderRadius: 28,
                            }}
                            animate={{
                                x: 0,
                                y: 0,
                                scale: 1,
                                opacity: 1,
                                borderRadius: 28,
                            }}
                            exit={{
                                x: offsetX,
                                y: offsetY,
                                scale: 0.45,
                                opacity: 0,
                                borderRadius: 28,
                            }}
                            transition={SPRING}
                            onClick={(e: React.MouseEvent) => e.stopPropagation()}
                        >
                            <motion.div
                                className="absolute -top-3 right-2 z-[2]"
                                initial={{opacity: 0, scale: 0.8}}
                                animate={{opacity: 1, scale: 1}}
                                exit={{opacity: 0, scale: 0.8}}
                                transition={{delay: 0.12, ...BACKDROP_TRANSITION}}
                            >
                                <TestableCompositeRemoveButton
                                    entityID={overlayState.id}
                                    show={true}
                                    onRequestToHighlight={() => {}}
                                    onRequestToUnHighlight={() => {}}
                                    onRemove={close}
                                />
                            </motion.div>
                            <div style={{maxWidth: '95vw'}}>
                                <InsideOverlayContext.Provider value={true}>
                                    <TestableComposite
                                        id={overlayState.id}
                                        color={colors.purple}
                                        isRoot={true}
                                        removable={false}
                                        forceExpanded
                                    />
                                </InsideOverlayContext.Provider>
                            </div>
                        </motion.div>
                        </div>
                    </div>
                </motion.div>
            )}
        </AnimatePresence>,
        document.body
    );
};
