import React, { useState, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { Group as GroupIcon, X, Edit2, Ungroup } from 'lucide-react';
import { cn } from '@/utils';
import { Group } from '../types/node';

interface GroupNodeProps {
  group: Group;
  isSelected: boolean;
  onSelect: () => void;
  onUpdate: (updates: Partial<Group>) => void;
  onDelete: () => void;
  onUngroup: () => void;
  onContextMenu?: (e: React.MouseEvent) => void;
  onDragStart?: () => void;
  onDrag?: (dx: number, dy: number) => void;
  onDragEnd?: () => void;
}

export function GroupNode({ 
  group, 
  isSelected, 
  onSelect, 
  onUpdate, 
  onDelete,
  onUngroup,
  onContextMenu,
  onDragStart,
  onDrag,
  onDragEnd
}: GroupNodeProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editTitle, setEditTitle] = useState(group.title);
  const [isDragging, setIsDragging] = useState(false);
  const dragStartRef = useRef({ x: 0, y: 0 });

  const handleTitleSubmit = useCallback(() => {
    onUpdate({ title: editTitle });
    setIsEditing(false);
  }, [editTitle, onUpdate]);

  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleTitleSubmit();
    } else if (e.key === 'Escape') {
      setEditTitle(group.title);
      setIsEditing(false);
    }
  }, [handleTitleSubmit, group.title]);

  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    if (isEditing) return;
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
    dragStartRef.current = { x: e.clientX, y: e.clientY };
    onDragStart?.();

    const handleMouseMove = (moveEvent: MouseEvent) => {
      const dx = moveEvent.clientX - dragStartRef.current.x;
      const dy = moveEvent.clientY - dragStartRef.current.y;
      onDrag?.(dx, dy);
    };

    const handleMouseUp = () => {
      setIsDragging(false);
      onDragEnd?.();
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', handleMouseUp);
    };

    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('mouseup', handleMouseUp);
  }, [isEditing, onDragStart, onDrag, onDragEnd]);

  return (
    <motion.div
      className={cn(
        "absolute rounded-xl border-2 transition-all duration-200 cursor-move",
        isSelected
          ? "border-cyan-500/80 bg-cyan-500/10"
          : "border-white/20 bg-white/5 hover:border-white/40",
        isDragging && "cursor-grabbing"
      )}
      style={{
        left: group.x,
        top: group.y,
        width: group.width,
        height: group.height,
      }}
      onClick={(e) => {
        e.stopPropagation();
        onSelect();
      }}
      onContextMenu={(e) => {
        e.preventDefault();
        e.stopPropagation();
        onContextMenu?.(e);
      }}
      onMouseDown={handleMouseDown}
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.95 }}
    >
      {/* Group Header */}
      <div className={cn(
        "absolute -top-6 left-0 flex items-center gap-2 px-2 py-1 rounded-t-lg text-xs font-medium transition-colors",
        isSelected
          ? "bg-cyan-500/80 text-white"
          : "bg-white/20 text-white/80"
      )}>
        <GroupIcon size={12} />

        {isEditing ? (
          <input
            type="text"
            value={editTitle}
            onChange={(e) => setEditTitle(e.target.value)}
            onBlur={handleTitleSubmit}
            onKeyDown={handleKeyDown}
            className="bg-transparent border-none outline-none text-white w-24 text-xs"
            autoFocus
            onClick={(e) => e.stopPropagation()}
          />
        ) : (
          <span
            className="cursor-pointer hover:text-white"
            onDoubleClick={(e) => {
              e.stopPropagation();
              setIsEditing(true);
            }}
          >
            {group.title}
          </span>
        )}
      </div>

      {/* Selection Indicator */}
      {isSelected && (
        <>
          {/* Resize handles - corners */}
          <div className="absolute -top-1 -left-1 w-2 h-2 bg-cyan-500 rounded-full" />
          <div className="absolute -top-1 -right-1 w-2 h-2 bg-cyan-500 rounded-full" />
          <div className="absolute -bottom-1 -left-1 w-2 h-2 bg-cyan-500 rounded-full" />
          <div className="absolute -bottom-1 -right-1 w-2 h-2 bg-cyan-500 rounded-full" />

          {/* Action buttons */}
          <div className="absolute -top-8 right-0 flex items-center gap-1">
            <button
              onClick={(e) => {
                e.stopPropagation();
                setIsEditing(true);
              }}
              className="p-1 bg-white/20 hover:bg-white/30 rounded text-white/80 hover:text-white transition-colors"
              title="重命名"
            >
              <Edit2 size={12} />
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                onUngroup();
              }}
              className="p-1 bg-white/20 hover:bg-white/30 rounded text-white/80 hover:text-white transition-colors"
              title="解散分组"
            >
              <Ungroup size={12} />
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                onDelete();
              }}
              className="p-1 bg-red-500/50 hover:bg-red-500/70 rounded text-white transition-colors"
              title="删除分组"
            >
              <X size={12} />
            </button>
          </div>
        </>
      )}
    </motion.div>
  );
}
