import React, { useState } from 'react';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from 'chart.js';
import { Line } from 'react-chartjs-2';
import '../styles/RangeChartModal.css';

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend);

interface RangeChartModalProps {
  isOpen: boolean;
  kpi: any;
  measurements: any[];
  getMeasurementsForRange: (days: number) => any[];
  onClose: () => void;
}

export const RangeChartModal: React.FC<RangeChartModalProps> = ({
  isOpen,
  kpi,
  measurements,
  getMeasurementsForRange,
  onClose,
}) => {
  const [selectedRange, setSelectedRange] = useState<number>(30);

  if (!isOpen || !kpi) return null;

  // Obtenir les mesures pour la plage sélectionnée
  const filteredMeasurements = getMeasurementsForRange(selectedRange);

  // Préparer les données pour le graphique
  const labels = filteredMeasurements
    .map(m => new Date(m.measurement_date).toLocaleDateString('fr-FR'))
    .reverse();
  
  const values = filteredMeasurements
    .map(m => m.value)
    .reverse();

  const chartData = {
    labels,
    datasets: [
      {
        label: kpi.name,
        data: values,
        borderColor: '#6496ff',
        backgroundColor: 'rgba(100, 150, 255, 0.1)',
        tension: 0.4,
        fill: true,
        pointRadius: 4,
        pointBackgroundColor: '#6496ff',
        pointBorderColor: '#fff',
        pointBorderWidth: 2,
      },
    ],
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: true,
        position: 'top' as const,
      },
      title: {
        display: true,
        text: `Graphique Complet: ${kpi.name}`,
        font: { size: 16, weight: 'bold' as const },
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        title: {
          display: true,
          text: kpi.unit,
        },
      },
      x: {
        display: true,
      },
    },
  };

  return (
    <div className="range-chart-modal-overlay" onClick={onClose}>
      <div className="range-chart-modal" onClick={(e) => e.stopPropagation()}>
        <div className="range-chart-modal-header">
          <h2>📈 {kpi.name}</h2>
          <button className="range-chart-modal-close" onClick={onClose}>✕</button>
        </div>

        <div className="range-chart-modal-range-selector">
          <label className={`range-option ${selectedRange === 7 ? 'active' : ''}`}>
            <input
              type="radio"
              name="chartRange"
              value="7"
              checked={selectedRange === 7}
              onChange={() => setSelectedRange(7)}
            />
            <span>📅 Semaine</span>
          </label>
          <label className={`range-option ${selectedRange === 30 ? 'active' : ''}`}>
            <input
              type="radio"
              name="chartRange"
              value="30"
              checked={selectedRange === 30}
              onChange={() => setSelectedRange(30)}
            />
            <span>📆 Mois</span>
          </label>
          <label className={`range-option ${selectedRange === 90 ? 'active' : ''}`}>
            <input
              type="radio"
              name="chartRange"
              value="90"
              checked={selectedRange === 90}
              onChange={() => setSelectedRange(90)}
            />
            <span>📊 Trimestre</span>
          </label>
          <label className={`range-option ${selectedRange === 365 ? 'active' : ''}`}>
            <input
              type="radio"
              name="chartRange"
              value="365"
              checked={selectedRange === 365}
              onChange={() => setSelectedRange(365)}
            />
            <span>📈 Année</span>
          </label>
          <label className={`range-option ${selectedRange === -1 ? 'active' : ''}`}>
            <input
              type="radio"
              name="chartRange"
              value="-1"
              checked={selectedRange === -1}
              onChange={() => setSelectedRange(-1)}
            />
            <span>🔄 Tout</span>
          </label>
        </div>

        <div className="range-chart-modal-body">
          <div style={{ height: '500px', width: '100%' }}>
            <Line data={chartData} options={chartOptions} />
          </div>
        </div>

        <div className="range-chart-modal-footer">
          <p>Mesures: <strong>{filteredMeasurements.length}</strong></p>
          <p>Période: <strong>{labels[0]} à {labels[labels.length - 1]}</strong></p>
        </div>
      </div>
    </div>
  );
};
