'use client';

import { useState, useRef, useEffect } from 'react';
import Image from 'next/image';
import { useIsMobile } from '@/hooks/use-mobile';

export default function DraggableWindose({ targetPosition, isVisible, onClose, onDragStart }: { targetPosition: { x: number; y: number } | null; isVisible: boolean; onClose: () => void; onDragStart?: () => void }) {
    const isMobile = useIsMobile();
    const [position, setPosition] = useState({ x: 100, y: 100 });
    const [isDragging, setIsDragging] = useState(false);
    const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
    const [shakeCount, setShakeCount] = useState(0);
    const windowRef = useRef<HTMLDivElement>(null);
    const lastPositionRef = useRef({ x: 100, y: 100 });
    const shakeThresholdRef = useRef(0);

    const handleMouseDown = (e: React.MouseEvent) => {
        if (e.button !== 0) return; // Only left click
        setIsDragging(true);
        setShakeCount(0);
        shakeThresholdRef.current = 0;
        onDragStart?.();
        if (windowRef.current) {
            const rect = windowRef.current.getBoundingClientRect();
            setDragOffset({
                x: e.clientX - rect.left,
                y: e.clientY - rect.top,
            });
        }
    };

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

        const handleMouseMove = (e: MouseEvent) => {
            const newX = e.clientX - dragOffset.x;
            const newY = e.clientY - dragOffset.y;
            
            setPosition({
                x: newX,
                y: newY,
            });

            // 흔드는 감지
            const distance = Math.sqrt(
                Math.pow(newX - lastPositionRef.current.x, 2) +
                Math.pow(newY - lastPositionRef.current.y, 2)
            );
            
            lastPositionRef.current = { x: newX, y: newY };
            shakeThresholdRef.current += distance;

            if (shakeThresholdRef.current > 2000) {
                setShakeCount(prev => prev + 1);
                shakeThresholdRef.current = 0;

                if (shakeCount >= 2) {
                    onClose();
                    setIsDragging(false);
                }
            }
        };

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

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

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

    // useEffect(() => {
    //     if (isDragging || targetPosition) return;

    //     const interval = setInterval(() => {
    //         setPosition({
    //             x: Math.random() * (window.innerWidth - 500),
    //             y: Math.random() * (window.innerHeight - 400),
    //         });
    //     }, 500);

    //     return () => clearInterval(interval);
    // }, [isDragging, targetPosition]);

    useEffect(() => {
        if (targetPosition && !isDragging) {
            setPosition(targetPosition);
        }
    }, [targetPosition, isDragging]);

    return (
        isMobile ? (
            <figure className="mb-8 w-full h-auto">
                <picture className="block bg-gray-100 rounded-xl aspect-3-2 overflow-hidden image-scale object-shadowed">
                    <Image
                        src="/full.webp"
                        alt="Banner"
                        width={1200}
                        height={400}
                        priority
                        className="object-cover object-center transition-transform duration-300 hover:scale-105" 
                    />
                </picture>
            </figure >
        ) : (
            isVisible && (
                <div
                    ref={windowRef}
                    className="fixed cursor-move select-none z-50"
                    style={{
                        left: `${position.x}px`,
                        top: `${position.y}px`,
                        transition: isDragging ? 'none' : targetPosition ? 'left 0.1s, top 0.1s' : 'left 0.4s ease-in-out, top 0.4s ease-in-out',
                    }}
                    onMouseDown={handleMouseDown}
                >
                    <div className="relative w-fit h-fit">
                        <Image
                            src="/windose.webp"
                            alt="Draggable Window"
                            width={500}
                            height={400}
                            priority
                            draggable={false}
                        />
                        <button
                            onClick={() => onClose()}
                            className="absolute top-1 right-2 w-5 h-5 cursor-pointer"
                            aria-label="Close window"
                        />
                    </div>
                </div>
            )
        )
    );
}
