import React, { useMemo } from "react";
import { RegionEvolutionPoint } from "../../../models/RegionEvolution";
import { colorForRegion } from "./timeseries.utils";
import "./TimeSeries.css";

type Props = {
  regionName: string;
  regionDetails: RegionEvolutionPoint[];
  hoverYear?: number;
  showClose?: boolean;
  onClose?: () => void;
};

export const TimeSeriesDetails: React.FC<Props> = ({
  regionName,
  regionDetails,
  hoverYear,
  showClose,
  onClose,
}) => {
  const stats = useMemo(() => {
    const rates = regionDetails.map((p) => p.rate);
    const min = Math.min(...rates);
    const max = Math.max(...rates);
    const avg = rates.reduce((s, v) => s + v, 0) / rates.length;
    return { min, max, avg, count: regionDetails.length };
  }, [regionDetails]);

  return (
    <div className="details-panel">
      <div className="details-header">
        <h3 className="details-title">{regionName}</h3>
        <div
          className="details-color-indicator"
          style={{ backgroundColor: colorForRegion(regionName) }}
        />
      </div>

      <div className="details-stats">
        <div className="stat-card">
          <span className="stat-label">Nombre de points</span>
          <span className="stat-value">{stats.count}</span>
        </div>

        <div className="stat-card">
          <span className="stat-label">Taux min</span>
          <span className="stat-value">{stats.min.toFixed(2)}</span>
        </div>

        <div className="stat-card">
          <span className="stat-label">Taux max</span>
          <span className="stat-value">{stats.max.toFixed(2)}</span>
        </div>

        <div className="stat-card">
          <span className="stat-label">Taux moyen</span>
          <span className="stat-value">{stats.avg.toFixed(2)}</span>
        </div>
      </div>

      <div className="details-table-wrapper">
        <table className="details-table">
          <thead>
            <tr>
              <th>Année</th>
              <th>Taux</th>
              <th>Code région</th>
            </tr>
          </thead>
          <tbody>
            {regionDetails.map((point) => (
              <tr
                key={point.id}
                className={hoverYear === point.year ? "highlighted" : ""}
              >
                <td>{point.year}</td>
                <td>{point.rate.toFixed(2)}</td>
                <td>{point.regionCode}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showClose && (
        <button className="close-details-button" onClick={onClose} type="button">
          Fermer les détails
        </button>
      )}
    </div>
  );
};
