import React, { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';
import { getCategoryColor, getCategoryName, getCategoryEmoji } from '../data/kpiData';
import { useSQLiteDatabase } from '../database/useSQLiteDatabase';
import { ChartModal } from '../components/ChartModal';
import { ExportModal } from '../components/ExportModal';
import { RangeChartModal } from '../components/RangeChartModal';
import '../styles/DetailPage.css';

interface DetailPageProps {
  category: 'security' | 'quality' | 'delays' | 'costs' | 'maintenance';
}

const categoryMap: Record<string, number> = {
  security: 1,
  quality: 2,
  delays: 3,
  costs: 4,
  maintenance: 5
};

export const DetailPage: React.FC<DetailPageProps> = ({ category }) => {
  const db = useSQLiteDatabase();
  const categoryId = categoryMap[category];
  const [selectedKPIId, setSelectedKPIId] = useState<number | null>(null);
  const [selectedKPIMeasurements, setSelectedKPIMeasurements] = useState<any[]>([]);
  const [selectedKPIStats, setSelectedKPIStats] = useState<any>(null);
  const [showChart, setShowChart] = useState(false);
  const [showExportModal, setShowExportModal] = useState(false);
  const [showChartRangeModal, setShowChartRangeModal] = useState(false);

  // Obtenir les KPI de cette catégorie
  const categoryKPIs = db.kpis.filter(kpi => kpi.category_id === categoryId);

  // Charger les mesures quand un KPI est sélectionné
  useEffect(() => {
    if (!selectedKPIId) {
      if (categoryKPIs.length > 0) {
        setSelectedKPIId(categoryKPIs[0].id);
      }
      return;
    }

    const fetchMeasurements = async () => {
      const measurements = await db.getMeasurementsForKPI(selectedKPIId, 365);
      const stats = await db.getKPIStats(selectedKPIId, 30);
      setSelectedKPIMeasurements(measurements || []);
      setSelectedKPIStats(stats);
    };

    fetchMeasurements();
  }, [selectedKPIId, categoryKPIs, db]);

  const selectedKPI = categoryKPIs.find(k => k.id === selectedKPIId);

  // Export to Excel
  const exportToExcel = (kpi: any, measurements: any[]) => {
    if (!kpi || measurements.length === 0) return;

    // Préparer les données
    const data = measurements.map(m => ({
      Date: new Date(m.measurement_date).toLocaleString('fr-FR'),
      Valeur: m.value,
      Statut: m.status,
    }));

    // Créer un classeur Excel
    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Mesures');

    // Ajouter une feuille de résumé
    const summary = [
      ['KPI', kpi.name],
      ['Unité', kpi.unit],
      ['Cible', kpi.target],
      ['Fréquence', kpi.frequency],
      ['Nombre de mesures', measurements.length],
      ['Date d\'export', new Date().toLocaleString('fr-FR')],
    ];
    
    const summarySheet = XLSX.utils.aoa_to_sheet(summary);
    XLSX.utils.book_append_sheet(workbook, summarySheet, 'Résumé');

    // Télécharger
    const filename = `${kpi.name.replace(/\s+/g, '_')}_${new Date().toISOString().split('T')[0]}.xlsx`;
    XLSX.writeFile(workbook, filename);
  };

  // Handle export with date range selection
  const handleExportClick = (days: number) => {
    if (!selectedKPI) return;
    
    let measurementsToExport = selectedKPIMeasurements;
    
    // Si l'utilisateur a sélectionné une plage spécifique (pas -1 pour tous)
    if (days > 0 && days !== 365) {
      measurementsToExport = selectedKPIMeasurements.filter((m: any) => {
        const daysAgo = (Date.now() - new Date(m.measurement_date).getTime()) / (1000 * 60 * 60 * 24);
        return daysAgo <= days;
      });
    }
    
    exportToExcel(selectedKPI, measurementsToExport);
  };

  // Get measurements for chart by date range
  const getMeasurementsForDateRange = (days: number) => {
    if (days === -1) return selectedKPIMeasurements;
    
    return selectedKPIMeasurements.filter((m: any) => {
      const daysAgo = (Date.now() - new Date(m.measurement_date).getTime()) / (1000 * 60 * 60 * 24);
      return daysAgo <= days;
    });
  };

  return (
    <div className="detail-page">
      <div className="detail-header">
        <h1 style={{ color: getCategoryColor(category) }}>
          {getCategoryEmoji(category)} {getCategoryName(category)}
        </h1>
        <p>Analyse détaillée des indicateurs</p>
      </div>

      <div className="detail-content">
        <div className="kpi-selector">
          <h3>Sélectionner un KPI</h3>
          
          <div className="action-buttons">
            <button 
              className="btn btn-export"
              onClick={() => setShowExportModal(true)}
              disabled={!selectedKPI}
            >
              📊 Exporter Excel
            </button>
            <button 
              className="btn btn-chart"
              onClick={() => setShowChartRangeModal(true)}
              disabled={!selectedKPI}
            >
              📈 Graphique Complet
            </button>
          </div>

          <div className="kpi-list">
            {categoryKPIs.map(kpi => (
              <button
                key={kpi.id}
                className={`kpi-option ${selectedKPIId === kpi.id ? 'active' : ''}`}
                onClick={() => setSelectedKPIId(kpi.id)}
              >
                <div className="kpi-name">{kpi.name}</div>
                <div className="kpi-unit">{kpi.unit}</div>
              </button>
            ))}
          </div>
        </div>

        {selectedKPI && (
          <div className="kpi-details">
            <div className="details-header">
              <h2>{selectedKPI.name}</h2>
              <div className="details-info">
                <div className="info-item">
                  <div className="info-label">Unité</div>
                  <div className="info-value">{selectedKPI.unit}</div>
                </div>
                <div className="info-item">
                  <div className="info-label">Cible</div>
                  <div className="info-value">{selectedKPI.target}</div>
                </div>
                <div className="info-item">
                  <div className="info-label">Fréquence</div>
                  <div className="info-value">{selectedKPI.frequency || 'N/A'}</div>
                </div>
              </div>
            </div>

            <div className="details-description">
              <h4>Description</h4>
              <p>{selectedKPI.description}</p>
              <h4>Formule</h4>
              <p>{selectedKPI.formula}</p>
            </div>

            {selectedKPIStats && (
              <div className="details-stats">
                <h4>Statistiques (30 derniers jours)</h4>
                <div className="stats-container">
                  <div className="stat-box">
                    <div className="stat-box-label">Moyenne</div>
                    <div className="stat-box-value">{selectedKPIStats.avg?.toFixed(2) || 'N/A'}</div>
                  </div>
                  <div className="stat-box">
                    <div className="stat-box-label">Min</div>
                    <div className="stat-box-value">{selectedKPIStats.min?.toFixed(2) || 'N/A'}</div>
                  </div>
                  <div className="stat-box">
                    <div className="stat-box-label">Max</div>
                    <div className="stat-box-value">{selectedKPIStats.max?.toFixed(2) || 'N/A'}</div>
                  </div>
                  <div className="stat-box">
                    <div className="stat-box-label">Mesures</div>
                    <div className="stat-box-value">{selectedKPIStats.count || 0}</div>
                  </div>
                </div>
              </div>
            )}

            <div className="measurements-section">
              <h4>Dernières mesures ({selectedKPIMeasurements.length})</h4>
              <table className="measurements-table">
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Valeur</th>
                    <th>Statut</th>
                  </tr>
                </thead>
                <tbody>
                  {selectedKPIMeasurements.slice(-10).reverse().map((m: any, idx: number) => (
                    <tr key={idx}>
                      <td>{new Date(m.measurement_date).toLocaleString('fr-FR')}</td>
                      <td>{m.value}</td>
                      <td>
                        <span className={`status-badge status-${m.status}`}>
                          {m.status === 'good' ? '✓ Bon' : m.status === 'warning' ? '⚠️ Attention' : '🔴 Critique'}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>

      <ChartModal 
        isOpen={showChart}
        kpi={selectedKPI}
        measurements={selectedKPIMeasurements}
        onClose={() => setShowChart(false)}
      />

      <ExportModal
        isOpen={showExportModal}
        kpiName={selectedKPI?.name || ''}
        onExport={handleExportClick}
        onClose={() => setShowExportModal(false)}
      />

      <RangeChartModal
        isOpen={showChartRangeModal}
        kpi={selectedKPI}
        measurements={selectedKPIMeasurements}
        getMeasurementsForRange={getMeasurementsForDateRange}
        onClose={() => setShowChartRangeModal(false)}
      />
    </div>
  );
};
