import { useState } from 'react';
import { AnimatePresence } from 'framer-motion';
import { DraggableChart } from './DraggableChart';
import { useHealthStore } from '../../store/useHealthStore';
import type { HealthMetric } from '../../types/medical';

export function HealthTrends() {
    const healthTrends = useHealthStore((state) => state.healthTrends);

    // State to track groups of metrics.
    // Each group represents a chart. A group can have 1 or more metrics.
    // Initial state: each metric is in its own group.
    const [chartGroups, setChartGroups] = useState<HealthMetric[][]>(() =>
        healthTrends.map(metric => [metric])
    );

    const handleMerge = (sourceGroupId: string, targetGroupId: string) => {
        setChartGroups(prevGroups => {
            const sourceGroupIndex = prevGroups.findIndex(g => g[0].id === sourceGroupId);
            const targetGroupIndex = prevGroups.findIndex(g => g[0].id === targetGroupId);

            if (sourceGroupIndex === -1 || targetGroupIndex === -1) return prevGroups;

            const newGroups = [...prevGroups];
            const sourceGroup = newGroups[sourceGroupIndex];

            // Add all metrics from source to target
            newGroups[targetGroupIndex] = [...newGroups[targetGroupIndex], ...sourceGroup];

            // Remove source group
            newGroups.splice(sourceGroupIndex, 1);

            return newGroups;
        });
    };

    const handleSeparate = (metricId: string, fromGroupId: string) => {
        setChartGroups(prevGroups => {
            const groupIndex = prevGroups.findIndex(g => g[0].id === fromGroupId);
            if (groupIndex === -1) return prevGroups;

            const group = prevGroups[groupIndex];

            // If group only has 1 item, nothing to separate
            if (group.length <= 1) return prevGroups;

            const metricToSeparate = group.find(m => m.id === metricId);
            if (!metricToSeparate) return prevGroups;

            const newGroups = [...prevGroups];

            // Remove metric from current group
            newGroups[groupIndex] = group.filter(m => m.id !== metricId);

            // Create new group for separated metric
            newGroups.push([metricToSeparate]);

            return newGroups;
        });
    };

    return (
        <div className="mt-8 animate-fade-in" style={{ animationDelay: '0.3s' }}>
            <div className="mb-6">
                <h2 className="text-xl font-bold text-gray-900">Health Trends</h2>
                <p className="text-sm text-gray-500">
                    Drag plots onto each other to compare trends.
                </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <AnimatePresence mode='popLayout'>
                    {chartGroups.map((group) => (
                        <DraggableChart
                            key={group[0].id} // Use the ID of the first metric as the group ID
                            groupId={group[0].id}
                            metrics={group}
                            onMerge={handleMerge}
                            onSeparate={handleSeparate}
                        />
                    ))}
                </AnimatePresence>
            </div>
        </div>
    );
}
