import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { X, Maximize2, Minimize2, GripHorizontal } from 'lucide-react';

interface DraggableResizableModalProps {
    isOpen: boolean;
    onClose: () => void;
    title: React.ReactNode;
    children: React.ReactNode;
    initialWidth?: number;
    initialHeight?: number;
    minWidth?: number;
    minHeight?: number;
}

export const DraggableResizableModal: React.FC<DraggableResizableModalProps> = ({
    isOpen,
    onClose,
    title,
    children,
    initialWidth = 800,
    initialHeight = 600,
    minWidth = 300,
    minHeight = 200
}) => {
    // State for window properties
    const [position, setPosition] = useState({ x: 0, y: 0 });
    const [size, setSize] = useState({ w: initialWidth, h: initialHeight });
    const [isMaximized, setIsMaximized] = useState(false);

    // Refs for drag/resize calculations
    const modalRef = useRef<HTMLDivElement>(null);
    const dragStartRef = useRef<{ x: number, y: number, initialX: number, initialY: number } | null>(null);
    const resizeStartRef = useRef<{ x: number, y: number, initialW: number, initialH: number } | null>(null);

    // Initialize position to center on first open
    useEffect(() => {
        if (isOpen && position.x === 0 && position.y === 0) {
            const x = (window.innerWidth - initialWidth) / 2;
            const y = (window.innerHeight - initialHeight) / 2;
            setPosition({ x: Math.max(0, x), y: Math.max(0, y) });
        }
    }, [isOpen, initialWidth, initialHeight, position.x, position.y]);

    // Global Event Listeners for Drag/Resize
    useEffect(() => {
        const handleMouseMove = (e: MouseEvent) => {
            if (dragStartRef.current) {
                const dx = e.clientX - dragStartRef.current.x;
                const dy = e.clientY - dragStartRef.current.y;
                setPosition({
                    x: dragStartRef.current.initialX + dx,
                    y: dragStartRef.current.initialY + dy
                });
            }
            if (resizeStartRef.current) {
                const dx = e.clientX - resizeStartRef.current.x;
                const dy = e.clientY - resizeStartRef.current.y;
                setSize({
                    w: Math.max(minWidth, resizeStartRef.current.initialW + dx),
                    h: Math.max(minHeight, resizeStartRef.current.initialH + dy)
                });
            }
        };

        const handleMouseUp = () => {
            dragStartRef.current = null;
            resizeStartRef.current = null;
            document.body.style.userSelect = '';
        };

        if (isOpen) {
            window.addEventListener('mousemove', handleMouseMove);
            window.addEventListener('mouseup', handleMouseUp);
        }

        return () => {
            window.removeEventListener('mousemove', handleMouseMove);
            window.removeEventListener('mouseup', handleMouseUp);
        };
    }, [isOpen, minWidth, minHeight]);

    // Handlers
    const handleDragStart = (e: React.MouseEvent) => {
        if (isMaximized) return; // Disable drag when maximized
        // Verify we are clicking the header and not a button
        if ((e.target as HTMLElement).closest('button')) return;

        dragStartRef.current = {
            x: e.clientX,
            y: e.clientY,
            initialX: position.x,
            initialY: position.y
        };
        document.body.style.userSelect = 'none'; // Prevent text selection
    };

    const handleResizeStart = (e: React.MouseEvent) => {
        e.stopPropagation();
        resizeStartRef.current = {
            x: e.clientX,
            y: e.clientY,
            initialW: size.w,
            initialH: size.h
        };
        document.body.style.userSelect = 'none';
    };

    const toggleMaximize = () => {
        if (!isMaximized) {
            // Save state before maximizing? (Optional, skipping for simplicity)
            setIsMaximized(true);
        } else {
            setIsMaximized(false);
        }
    };

    if (!isOpen) return null;

    // Use current state or full screen if maximized
    // };

    // Correction: In strict mode JSX, duplicate keys are bad. Rewriting style object cleanly.
    const modalStyle: React.CSSProperties = isMaximized
        ? {
            position: 'fixed' as const,
            top: 0,
            left: 0,
            width: '100vw',
            height: '100vh',
            borderRadius: 0,
            zIndex: 100
        }
        : {
            position: 'fixed' as const,
            top: position.y,
            left: position.x,
            width: size.w,
            height: size.h,
            zIndex: 100
        };

    return createPortal(
        <div className="fixed inset-0 z-[90] pointer-events-none">
            {/* Backdrop - optional, maybe just transparent or dimmed but clickable? 
                User said "pop up", usually implies modal. 
                Let's keep a dimmed backdrop but make it non-blocking if we wanted true "window" feel,
                but for now let's stick to standard modal behavior: blocking backdrop.
            */}
            <div
                className="absolute inset-0 bg-black/30 backdrop-blur-[1px] pointer-events-auto"
                onClick={onClose}
            />

            {/* Window */}
            <div
                ref={modalRef}
                style={modalStyle}
                className="bg-white shadow-2xl flex flex-col pointer-events-auto border border-gray-200 overflow-hidden rounded-xl animate-in fade-in zoom-in-95 duration-200"
            >
                {/* Header / Drag Handle */}
                <div
                    onMouseDown={handleDragStart}
                    className={`
                        h-12 bg-gray-50 border-b border-gray-100 flex items-center justify-between px-4 select-none
                        ${isMaximized ? '' : 'cursor-grab active:cursor-grabbing'}
                    `}
                >
                    <div className="flex items-center gap-2 text-gray-700 font-semibold truncate">
                        <GripHorizontal className="w-4 h-4 text-gray-400" />
                        <span className="truncate">{title}</span>
                    </div>
                    <div className="flex items-center gap-2">
                        <button
                            onClick={toggleMaximize}
                            className="p-1.5 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700"
                            title={isMaximized ? "Restore" : "Maximize"}
                        >
                            {isMaximized ? <Minimize2 size={16} /> : <Maximize2 size={16} />}
                        </button>
                        <button
                            onClick={onClose}
                            className="p-1.5 hover:bg-red-100 rounded text-gray-500 hover:text-red-600"
                            title="Close"
                        >
                            <X size={16} />
                        </button>
                    </div>
                </div>

                {/* Content */}
                <div className="flex-1 overflow-hidden relative">
                    {children}
                </div>

                {/* Resize Handle (only show if not maximized) */}
                {!isMaximized && (
                    <div
                        onMouseDown={handleResizeStart}
                        className="absolute bottom-0 right-0 w-6 h-6 cursor-nwse-resize flex items-center justify-center z-10 hover:bg-gray-100 rounded-tl"
                    >
                        <div className="w-2 h-2 border-r-2 border-b-2 border-gray-400 mb-1 mr-1"></div>
                    </div>
                )}
            </div>
        </div>,
        document.body
    );
};
