import { useMemo } from 'react';
import {
    LineChart,
    Line,
    XAxis,
    YAxis,
    CartesianGrid,
    Tooltip,
    ResponsiveContainer,
    Legend
} from 'recharts';
import type { HealthMetric } from '../../types/medical';
import { formatDate } from '../../utils/helpers';

interface SmartChartProps {
    metrics: HealthMetric[];
    height?: number;
}

export function SmartChart({ metrics, height = 300 }: SmartChartProps) {
    // Combine data from all metrics into a single array for the chart
    const chartData = useMemo(() => {
        if (metrics.length === 0) return [];

        // Get all unique dates across all metrics
        const allDates = new Set<string>();
        metrics.forEach(metric => {
            metric.data.forEach(point => allDates.add(point.date));
        });

        // Create a sorted array of dates
        const sortedDates = Array.from(allDates).sort();

        // Map each date to a data object containing values for each metric
        return sortedDates.map(date => {
            const dataPoint: any = { date };
            metrics.forEach(metric => {
                const point = metric.data.find(d => d.date === date);
                if (point) {
                    dataPoint[metric.id] = point.value;
                }
            });
            return dataPoint;
        });
    }, [metrics]);

    if (metrics.length === 0) {
        return (
            <div className="flex items-center justify-center h-full text-gray-400">
                No data available
            </div>
        );
    }

    return (
        <div style={{ height }} className="w-full min-w-[100px]">
            <ResponsiveContainer width="100%" height="100%" minWidth={100}>
                <LineChart data={chartData} margin={{ top: 10, right: 30, left: 0, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f0f0f0" />
                    <XAxis
                        dataKey="date"
                        tickFormatter={(value) => formatDate(value)}
                        stroke="#9ca3af"
                        fontSize={12}
                        tickLine={false}
                        axisLine={false}
                        dy={10}
                    />

                    {/* Generate Y-Axes based on metrics */}
                    {metrics.map((metric, index) => (
                        <YAxis
                            key={metric.id}
                            yAxisId={metric.id}
                            orientation={index % 2 === 0 ? 'left' : 'right'}
                            stroke={metric.color}
                            fontSize={12}
                            tickLine={false}
                            axisLine={false}
                            unit={metrics.length === 1 ? ` ${metric.unit}` : ''}
                            width={60}
                        />
                    ))}

                    <Tooltip
                        contentStyle={{
                            backgroundColor: 'rgba(255, 255, 255, 0.95)',
                            borderRadius: '8px',
                            border: 'none',
                            boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)',
                            fontSize: '12px'
                        }}
                        labelFormatter={(value) => formatDate(value as string)}
                    />

                    {metrics.length > 1 && <Legend />}

                    {/* Generate Lines */}
                    {metrics.map((metric) => (
                        <Line
                            key={metric.id}
                            yAxisId={metric.id}
                            type="monotone"
                            dataKey={metric.id}
                            name={metric.name}
                            stroke={metric.color}
                            strokeWidth={3}
                            dot={{ r: 4, strokeWidth: 2, fill: '#fff' }}
                            activeDot={{ r: 6, strokeWidth: 0 }}
                            connectNulls
                            animationDuration={1500}
                            animationEasing="ease-in-out"
                        />
                    ))}
                </LineChart>
            </ResponsiveContainer>
        </div>
    );
}
