import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Paper } from '@mui/material';

/**
 * 드래그 가능한 Dialog Paper — tam 스타일 팝업, 마운트 시 화면 중앙 배치
 */
const DraggablePaper = (props: any) => {
  const paperRef = useRef<HTMLDivElement>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
  const centeredOnce = useRef(false);

  useEffect(() => {
    if (centeredOnce.current) return;
    const el = paperRef.current;
    if (!el) return;
    const placeCenter = () => {
      const w = el.offsetWidth || 400;
      const h = el.offsetHeight || 320;
      setPosition({
        x: Math.max(8, (window.innerWidth - w) / 2),
        y: Math.max(8, (window.innerHeight - h) / 2),
      });
      centeredOnce.current = true;
    };
    placeCenter();
    const id = requestAnimationFrame(placeCenter);
    return () => cancelAnimationFrame(id);
  }, []);

  const handleMouseDown = (e: React.MouseEvent) => {
    const target = e.target as HTMLElement;
    if (target.closest('.MuiDialogTitle-root') &&
        !target.closest('button') &&
        !target.closest('.MuiButton-root') &&
        !target.closest('.MuiIconButton-root')) {
      setIsDragging(true);
      setDragStart({
        x: e.clientX - position.x,
        y: e.clientY - position.y,
      });
    }
  };

  const handleMouseMove = useCallback((e: MouseEvent) => {
    if (isDragging && paperRef.current) {
      setPosition({
        x: e.clientX - dragStart.x,
        y: Math.max(0, e.clientY - dragStart.y),
      });
    }
  }, [isDragging, dragStart]);

  const handleMouseUp = useCallback(() => {
    setIsDragging(false);
  }, []);

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

  return (
    <Paper
      {...props}
      ref={paperRef}
      onMouseDown={handleMouseDown}
      sx={{
        ...props.sx,
        position: 'fixed',
        top: position.y,
        left: position.x,
        margin: 0,
        cursor: isDragging ? 'grabbing' : 'default',
        borderRadius: '12px',
        border: '1px solid rgba(63, 126, 245, 0.35)',
        backgroundImage: 'none',
        backgroundColor: '#1e222d',
        boxShadow: '0 0 0 1px rgba(63,126,245,0.08), 0 20px 60px rgba(0,0,0,0.65), 0 0 40px rgba(63,126,245,0.06)',
        overflow: 'hidden',
        '& .MuiDialogTitle-root': {
          cursor: 'grab',
          userSelect: 'none',
          background: 'linear-gradient(180deg, rgba(63,126,245,0.14) 0%, rgba(63,126,245,0.04) 28px, #1f2335 100%)',
          borderBottom: '1px solid rgba(122,162,247,0.12)',
          color: '#c0caf5',
          fontSize: '14px',
          fontWeight: 700,
          '&:active': { cursor: 'grabbing' },
        },
        '& .MuiDialogContent-root': {
          bgcolor: '#1e222d',
          color: '#c0caf5',
        },
        '& .MuiDialogActions-root': {
          bgcolor: '#1e222d',
          borderTop: '1px solid rgba(122,162,247,0.1)',
        },
      }}
    />
  );
};

export default DraggablePaper;
