import React from 'react';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from 'chart.js';
import { Line } from 'react-chartjs-2';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from './ui/dialog';
import { LineChart } from 'lucide-react';

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

interface ChartModalProps {
  isOpen: boolean;
  kpi: any;
  measurements: any[];
  onClose: () => void;
}

export const ChartModal: React.FC<ChartModalProps> = ({ isOpen, kpi, measurements, onClose }) => {
  if (!kpi) return null;

  const labels = measurements
    .map(m => new Date(m.measurement_date).toLocaleDateString('fr-FR'))
    .reverse();

  const values = measurements
    .map(m => m.value)
    .reverse();

  const chartData = {
    labels,
    datasets: [
      {
        label: kpi.name,
        data: values,
        borderColor: '#60a5fa',
        backgroundColor: 'rgba(96, 165, 250, 0.1)',
        tension: 0.4,
        fill: true,
        pointRadius: 4,
        pointBackgroundColor: '#60a5fa',
        pointBorderColor: '#1e293b',
        pointBorderWidth: 2,
      },
    ],
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: true,
        position: 'top' as const,
        labels: {
          color: '#cbd5e1',
        },
      },
      title: {
        display: false,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        title: {
          display: true,
          text: kpi.unit,
          color: '#cbd5e1',
        },
        ticks: {
          color: '#94a3b8',
        },
        grid: {
          color: 'rgba(148, 163, 184, 0.1)',
        },
      },
      x: {
        display: true,
        ticks: {
          color: '#94a3b8',
        },
        grid: {
          color: 'rgba(148, 163, 184, 0.1)',
        },
      },
    },
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[800px] max-h-[90vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <LineChart className="h-5 w-5" />
            {kpi.name}
          </DialogTitle>
          <DialogDescription>
            Nombre de mesures: {measurements.length} | Période: {labels[0]} à {labels[labels.length - 1]}
          </DialogDescription>
        </DialogHeader>

        <div className="py-4">
          <div style={{ height: '500px', width: '100%' }}>
            <Line data={chartData} options={chartOptions} />
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};
