import React, { useCallback, useEffect, useRef, useState } from 'react';

import './StudioInsertionPopup.css';

const DEFAULT_POS = { x: 72, y: 96 };

function StudioInsertionPopup({ open, title, onClose, defaultExpanded = false, children }) {
  const popupRef = useRef(null);
  const dragRef = useRef(null);
  const [pos, setPos] = useState(DEFAULT_POS);
  const [expanded, setExpanded] = useState(defaultExpanded);

  useEffect(() => {
    if (open) {
      setExpanded(defaultExpanded);
      setPos(DEFAULT_POS);
    }
  }, [open, defaultExpanded]);

  const handleDragStart = useCallback((e) => {
    if (e.button !== 0) return;
    e.preventDefault();
    const startX = e.clientX;
    const startY = e.clientY;
    const origin = { ...pos };

    const onMove = (ev) => {
      setPos({
        x: origin.x + (ev.clientX - startX),
        y: origin.y + (ev.clientY - startY),
      });
    };

    const onUp = () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      dragRef.current = null;
    };

    dragRef.current = { startX, startY, origin };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  }, [pos]);

  useEffect(() => {
    return () => {
      if (dragRef.current) {
        window.removeEventListener('mousemove', () => {});
        window.removeEventListener('mouseup', () => {});
      }
    };
  }, []);

  if (!open) return null;

  return (
    <div
      ref={popupRef}
      className={`studio-insertion-popup${expanded ? ' is-expanded' : ''}`}
      style={{ left: pos.x, top: pos.y }}
      role="dialog"
      aria-label={title}
    >
      <div
        className="studio-insertion-popup__header"
        onMouseDown={handleDragStart}
      >
        <span className="studio-insertion-popup__title">{title}</span>
        <div className="studio-insertion-popup__actions">
          <button
            type="button"
            className="studio-insertion-popup__btn"
            onClick={() => setExpanded((v) => !v)}
            title={expanded ? '收起详情' : '展开详情'}
          >
            {expanded ? '收起' : '展开'}
          </button>
          <button
            type="button"
            className="studio-insertion-popup__btn studio-insertion-popup__btn--close"
            onClick={onClose}
            aria-label="关闭"
          >
            ×
          </button>
        </div>
      </div>
      <div className="studio-insertion-popup__body">
        {children({ expanded })}
      </div>
    </div>
  );
}

export default StudioInsertionPopup;
