import { useState } from 'react';
import { motion } from 'framer-motion';
import { GripVertical, X } from 'lucide-react';
import { SmartChart } from './SmartChart';
import type { HealthMetric } from '../../types/medical';

interface DraggableChartProps {
    groupId: string;
    metrics: HealthMetric[];
    onMerge: (sourceGroupId: string, targetGroupId: string) => void;
    onSeparate: (metricId: string, fromGroupId: string) => void;
}

export function DraggableChart({ groupId, metrics, onMerge, onSeparate }: DraggableChartProps) {
    const [isOver, setIsOver] = useState(false);

    const handleDragStart = (e: React.DragEvent) => {
        e.dataTransfer.setData('text/plain', groupId);
        e.dataTransfer.effectAllowed = 'move';
        // Make the drag image transparent or custom if needed, 
        // but default browser ghost is usually fine for this size
    };

    const handleDragOver = (e: React.DragEvent) => {
        e.preventDefault(); // Necessary to allow dropping
        e.dataTransfer.dropEffect = 'move';
        if (!isOver) setIsOver(true);
    };

    const handleDragLeave = () => {
        setIsOver(false);
    };

    const handleDrop = (e: React.DragEvent) => {
        e.preventDefault();
        setIsOver(false);
        const sourceGroupId = e.dataTransfer.getData('text/plain');

        if (sourceGroupId && sourceGroupId !== groupId) {
            onMerge(sourceGroupId, groupId);
        }
    };

    return (
        <motion.div
            layout
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.9 }}
            transition={{ duration: 0.2 }}
            className={`
        relative bg-white rounded-2xl shadow-sm border-2 transition-colors duration-200
        ${isOver ? 'border-blue-500 bg-blue-50' : 'border-transparent hover:border-gray-200'}
      `}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
        >
            {/* Header - Draggable Handle */}
            <div
                className="flex items-center justify-between p-4 border-b border-gray-100 cursor-grab active:cursor-grabbing"
                draggable
                onDragStart={handleDragStart}
            >
                <div className="flex items-center gap-2">
                    <GripVertical className="w-4 h-4 text-gray-400" />
                    <div className="flex flex-wrap gap-2">
                        {metrics.map(metric => (
                            <div
                                key={metric.id}
                                className="flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-opacity-10"
                                style={{ backgroundColor: metric.color + '20', color: metric.color }}
                            >
                                {metric.name}
                                {metrics.length > 1 && (
                                    <button
                                        onClick={(e) => {
                                            e.stopPropagation(); // Prevent drag start
                                            onSeparate(metric.id, groupId);
                                        }}
                                        className="hover:bg-black hover:bg-opacity-10 rounded-full p-0.5 ml-1"
                                    >
                                        <X className="w-3 h-3" />
                                    </button>
                                )}
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            {/* Chart Content */}
            <div className="p-4">
                <SmartChart metrics={metrics} height={250} />
            </div>
        </motion.div>
    );
}
