import React, { useState, useEffect, useRef } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

export interface DataPoint {
  target: string;
  time: number;
  value: number;
}

interface SlidingWindowXYLineChartProps {
  currentValue?: DataPoint;
}

const SlidingWindowXYLineChart: React.FC<SlidingWindowXYLineChartProps> = ({ currentValue }) => {
  const [data, setData] = useState<DataPoint[]>([]);
  const [yDomain, setYDomain] = useState<[number, number]>([0, 1]);
  const [xDomain, setXDomain] = useState<[number, number]>([0, 1]);
  const windowDuration = 5000; // 5 seconds in milliseconds

  useEffect(() => {
    if (currentValue) {
      setData(prevData => {
        const newData = [...prevData, currentValue];
        const now = currentValue.time;
        const filteredData = newData.filter(point => now - point.time <= windowDuration);
        
        if (filteredData.length > 0) {
          const values = filteredData.map(d => d.value);
          const times = filteredData.map(d => d.time);
          const minValue = Math.min(...values);
          const maxValue = Math.max(...values);
          const minTime = Math.min(...times);
          const maxTime = Math.max(...times);
          
          setYDomain([
            Math.max(0, Math.floor(minValue * 0.9)),
            Math.ceil(maxValue * 1.1)
          ]);
          
          setXDomain([minTime, maxTime]);
        }

        console.log("Updated data:", filteredData); // Debugging log
        return filteredData;
      });
    }
  }, [currentValue]);

  const formatXAxis = (timestamp: number) => {
    const date = new Date(timestamp);
    return `${date.getSeconds()}.${date.getMilliseconds().toString().padStart(3, '0')}`;
  };

  console.log("Rendering with data:", data); // Debugging log

  if (data.length === 0) {
    return <div>No data available</div>;
  }

  return (
    <div className="bg-gray-700 rounded mt-4 mb-4">
      <ResponsiveContainer width="100%" height={300}>
        <LineChart data={data} margin={{ top: 30, right: 30, bottom: 20, left: 0 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="#555" />
          <XAxis 
            dataKey="time"
            type="number"
            domain={xDomain}
            tickFormatter={formatXAxis}
            stroke="#888"
          />
          <YAxis 
            type="number"
            dataKey="value"
            name="Value" 
            stroke="#888"
            domain={yDomain}
          />
          <Tooltip 
            labelFormatter={(label) => `Time: ${formatXAxis(label as number)}s`}
            formatter={(value, name, props) => [`${value}`, props.payload.target]}
            contentStyle={{ backgroundColor: '#333', border: '1px solid #555' }}
          />
          <Line 
            isAnimationActive={false}
            type="monotone" 
            dataKey="value" 
            stroke="#8884d8" 
            dot={false} 
            strokeWidth={2}
          />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
};

export default SlidingWindowXYLineChart;