import { ResponsiveContainer, ScatterChart, Scatter, XAxis, YAxis, ZAxis, Tooltip, Cell, CartesianGrid, Line } from 'recharts';
import { Card } from '../common/Card';

interface ParetoPlotProps {
  data: any[];
  xKey: string;
  yKey: string;
  zKey?: string;
}

export const ParetoPlot = ({ data, xKey, yKey, zKey }: ParetoPlotProps) => {
  // Filter out null/undefined data points
  const validData = data.filter(d =>
    d &&
    d[xKey] !== null && d[xKey] !== undefined &&
    d[yKey] !== null && d[yKey] !== undefined
  );

  if (validData.length === 0) {
    return (
      <Card title="Pareto Front Evolution">
        <div className="h-80 flex items-center justify-center text-dark-300">
          No Pareto front data yet
        </div>
      </Card>
    );
  }

  // Sort data by x-coordinate for Pareto front line
  const sortedData = [...validData].sort((a, b) => a[xKey] - b[xKey]);

  return (
    <Card title="Pareto Front Evolution">
      <div className="h-80">
        <ResponsiveContainer width="100%" height="100%">
          <ScatterChart margin={{ top: 20, right: 20, bottom: 40, left: 60 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
            <XAxis
              type="number"
              dataKey={xKey}
              name={xKey}
              stroke="#94a3b8"
              label={{ value: xKey, position: 'insideBottom', offset: -30, fill: '#94a3b8' }}
            />
            <YAxis
              type="number"
              dataKey={yKey}
              name={yKey}
              stroke="#94a3b8"
              label={{ value: yKey, angle: -90, position: 'insideLeft', offset: -40, fill: '#94a3b8' }}
            />
            {zKey && <ZAxis type="number" dataKey={zKey} range={[50, 400]} name={zKey} />}
            <Tooltip
              cursor={{ strokeDasharray: '3 3' }}
              contentStyle={{ backgroundColor: '#1e293b', border: 'none', borderRadius: '8px' }}
              labelStyle={{ color: '#e2e8f0' }}
              formatter={(value: any) => {
                if (typeof value === 'number') {
                  return value.toFixed(2);
                }
                return value;
              }}
            />
            {/* Pareto front line */}
            <Line
              type="monotone"
              data={sortedData}
              dataKey={yKey}
              stroke="#8b5cf6"
              strokeWidth={2}
              dot={false}
              connectNulls={false}
              isAnimationActive={false}
            />
            <Scatter name="Pareto Front" data={validData} fill="#8884d8">
              {validData.map((entry, index) => (
                <Cell key={`cell-${index}`} fill={entry.isPareto !== false ? '#10b981' : '#60a5fa'} r={6} />
              ))}
            </Scatter>
          </ScatterChart>
        </ResponsiveContainer>
      </div>
    </Card>
  );
};