import React, { useRef, useState, useEffect } from 'react';
import { X, Minus, Maximize2, Minimize2 } from 'lucide-react';
import { Button } from '@/components/ui/button';

interface DraggableWindowProps {
    id: string;
    title: string;
    children: React.ReactNode;
    onClose: () => void;
    onMinimize: () => void;
    isActive: boolean;
    onFocus: () => void;
    initialPosition?: { x: number; y: number };
    initialSize?: { width: number; height: number };
}

export const DraggableWindow: React.FC<DraggableWindowProps> = ({
    id,
    title,
    children,
    onClose,
    onMinimize,
    isActive,
    onFocus,
    initialPosition = { x: 100, y: 100 },
    initialSize = { width: 1200, height: 700 },
}) => {
    const windowRef = useRef<HTMLDivElement>(null);
    const headerRef = useRef<HTMLDivElement>(null);
    const [isDragging, setIsDragging] = useState(false);
    const [isResizing, setIsResizing] = useState(false);
    const [position, setPosition] = useState(initialPosition);
    const [size, setSize] = useState(initialSize);
    const [isMaximized, setIsMaximized] = useState(false);
    const [savedState, setSavedState] = useState({ position: initialPosition, size: initialSize });
    const dragStartRef = useRef({ x: 0, y: 0 });
    const resizeStartRef = useRef({ x: 0, y: 0, width: 0, height: 0 });

    // 拖动开始
    const handleDragStart = (e: React.MouseEvent) => {
        if (isMaximized) return;
        setIsDragging(true);
        dragStartRef.current = {
            x: e.clientX - position.x,
            y: e.clientY - position.y,
        };
        onFocus();
        e.preventDefault();
    };

    // 拖动中
    useEffect(() => {
        if (!isDragging) return;

        const handleMouseMove = (e: MouseEvent) => {
            const newX = e.clientX - dragStartRef.current.x;
            const newY = e.clientY - dragStartRef.current.y;
            
            // 限制在可见区域内
            const maxX = window.innerWidth - size.width;
            const maxY = window.innerHeight - size.height;
            
            setPosition({
                x: Math.max(0, Math.min(newX, maxX)),
                y: Math.max(0, Math.min(newY, maxY)),
            });
        };

        const handleMouseUp = () => {
            setIsDragging(false);
        };

        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', handleMouseUp);

        return () => {
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
        };
    }, [isDragging, size.width, size.height]);

    // 调整大小开始
    const handleResizeStart = (e: React.MouseEvent) => {
        if (isMaximized) return;
        setIsResizing(true);
        resizeStartRef.current = {
            x: e.clientX,
            y: e.clientY,
            width: size.width,
            height: size.height,
        };
        onFocus();
        e.preventDefault();
        e.stopPropagation();
    };

    // 调整大小中
    useEffect(() => {
        if (!isResizing) return;

        const handleMouseMove = (e: MouseEvent) => {
            const deltaX = e.clientX - resizeStartRef.current.x;
            const deltaY = e.clientY - resizeStartRef.current.y;
            
            // 限制窗口大小不超出屏幕
            const newWidth = Math.max(600, resizeStartRef.current.width + deltaX);
            const newHeight = Math.max(400, resizeStartRef.current.height + deltaY);
            const maxWidth = window.innerWidth - position.x;
            const maxHeight = window.innerHeight - position.y;
            
            setSize({
                width: Math.min(newWidth, maxWidth),
                height: Math.min(newHeight, maxHeight),
            });
        };

        const handleMouseUp = () => {
            setIsResizing(false);
            // 触发 resize 事件通知终端调整大小
            setTimeout(() => {
                window.dispatchEvent(new Event('resize'));
            }, 50);
        };

        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', handleMouseUp);

        return () => {
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
        };
    }, [isResizing, position.x, position.y]);

    // 最大化/还原
    const toggleMaximize = () => {
        if (!isMaximized) {
            setSavedState({ position, size });
            setPosition({ x: 0, y: 0 });
            setSize({ width: window.innerWidth, height: window.innerHeight });
        } else {
            setPosition(savedState.position);
            setSize(savedState.size);
        }
        setIsMaximized(!isMaximized);
        
        // 触发 resize 事件通知终端调整大小
        setTimeout(() => {
            window.dispatchEvent(new Event('resize'));
        }, 250);
    };

    // 双击标题栏最大化
    const handleHeaderDoubleClick = () => {
        toggleMaximize();
    };

    const zIndex = isActive ? 1000 : 999;

    return (
        <div
            ref={windowRef}
            className="fixed bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg shadow-2xl flex flex-col overflow-hidden"
            style={{
                left: `${position.x}px`,
                top: `${position.y}px`,
                width: `${size.width}px`,
                height: `${size.height}px`,
                zIndex,
                transition: isMaximized ? 'all 0.2s ease' : 'none',
            }}
            onMouseDown={onFocus}
        >
            {/* 窗口标题栏 */}
            <div
                ref={headerRef}
                className={`flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700 cursor-move select-none ${
                    isActive ? 'bg-blue-50 dark:bg-blue-900/20' : 'bg-gray-50 dark:bg-gray-800'
                }`}
                onMouseDown={handleDragStart}
                onDoubleClick={handleHeaderDoubleClick}
            >
                <div className="flex-1 font-semibold text-gray-900 dark:text-gray-100">
                    {title}
                </div>
                <div className="flex items-center gap-2">
                    <Button
                        size="sm"
                        variant="ghost"
                        className="h-8 w-8 p-0"
                        onClick={onMinimize}
                    >
                        <Minus className="h-4 w-4" />
                    </Button>
                    <Button
                        size="sm"
                        variant="ghost"
                        className="h-8 w-8 p-0"
                        onClick={toggleMaximize}
                    >
                        {isMaximized ? (
                            <Minimize2 className="h-4 w-4" />
                        ) : (
                            <Maximize2 className="h-4 w-4" />
                        )}
                    </Button>
                    <Button
                        size="sm"
                        variant="ghost"
                        className="h-8 w-8 p-0 hover:bg-red-100 hover:text-red-600"
                        onClick={onClose}
                    >
                        <X className="h-4 w-4" />
                    </Button>
                </div>
            </div>

            {/* 窗口内容 */}
            <div className="flex-1 overflow-hidden">
                {children}
            </div>

            {/* 调整大小手柄 */}
            {!isMaximized && (
                <div
                    className="absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize"
                    onMouseDown={handleResizeStart}
                    style={{
                        background: 'linear-gradient(135deg, transparent 50%, #999 50%)',
                    }}
                />
            )}
        </div>
    );
};
