import React, { useState, useEffect } from 'react';
import { KPICard } from '../components/KPICard';
import { getCategoryColor } from '../data/kpiData';
import { useSQLiteDatabase } from '../database/useSQLiteDatabase';
import '../styles/HomePage.css';

export const HomePage: React.FC = () => {
  const db = useSQLiteDatabase();
  const [timeRange, setTimeRange] = useState<'today' | 'week' | 'last7' | 'month' | 'year'>('today');
  const [stats, setStats] = useState({ total: 0, good: 0, warning: 0, critical: 0 });
  const [topKPIs, setTopKPIs] = useState<any>({});
  const [avgPerformance, setAvgPerformance] = useState(0);
  const [criticalAlerts, setCriticalAlerts] = useState<any[]>([]);

  // Convertir la plage de temps en nombre de jours
  const getDaysFromTimeRange = (range: 'today' | 'week' | 'last7' | 'month' | 'year'): number => {
    switch (range) {
      case 'today':
        return 0;
      case 'week': {
        const today = new Date();
        const dayOfWeek = today.getDay();
        const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
        return daysFromMonday;
      }
      case 'last7':
        return 7;
      case 'month':
        return 30;
      case 'year':
        return 365;
      default:
        return 0;
    }
  };

  // Charger les données quand les KPI changent ou que la plage change
  useEffect(() => {
    if (db.loading || db.kpis.length === 0) return;

    const fetchData = async () => {
      const days = getDaysFromTimeRange(timeRange);
      const kpisWithStatus: any[] = [];
      const alertList: any[] = [];

      // Charger les mesures pour chaque KPI
      for (const kpi of db.kpis) {
        const measurements = await db.getMeasurementsForKPI(kpi.id, days);
        
        let status = 'good';
        let value = 0;

        if (measurements && measurements.length > 0) {
          const values = measurements.map((m: any) => m.value);
          value = Math.round((values.reduce((a: number, b: number) => a + b, 0) / values.length) * 100) / 100;

          const tolerance = kpi.target! * 0.1;
          
          if ([2, 4, 5, 6, 13, 16].includes(kpi.id)) {
            if (value > kpi.target! + tolerance * 2) status = 'critical';
            else if (value > kpi.target! + tolerance) status = 'warning';
            else status = 'good';
          } else {
            if (value < kpi.target! - tolerance * 2) status = 'critical';
            else if (value < kpi.target! - tolerance) status = 'warning';
            else status = 'good';
          }

          if (status === 'critical' || status === 'warning') {
            alertList.push({ ...kpi, status, value });
          }
        }

        kpisWithStatus.push({ ...kpi, status, value });
      }

      // Calculer les statistiques
      const statCounts = {
        total: kpisWithStatus.length,
        good: kpisWithStatus.filter(k => k.status === 'good').length,
        warning: kpisWithStatus.filter(k => k.status === 'warning').length,
        critical: kpisWithStatus.filter(k => k.status === 'critical').length
      };

      // Grouper par catégorie
      const topKPIsMap: any = {};
      [1, 2, 3, 4, 5].forEach(catId => {
        topKPIsMap[catId] = kpisWithStatus
          .filter(k => k.category_id === catId)
          .slice(0, 2);
      });

      // Performance globale
      const performance = Math.round(
        ((statCounts.good * 100 + statCounts.warning * 50) / (statCounts.total * 100)) * 100
      );

      setStats(statCounts);
      setTopKPIs(topKPIsMap);
      setAvgPerformance(performance);
      setCriticalAlerts(alertList.sort((a, b) => {
        if (a.status === 'critical' && b.status !== 'critical') return -1;
        if (a.status !== 'critical' && b.status === 'critical') return 1;
        return 0;
      }).slice(0, 4));
    };

    fetchData();
  }, [db, timeRange]);

  if (db.loading) {
    return (
      <div className="home-page">
        <div className="stats-overview">
          <p style={{ textAlign: 'center', padding: '2rem' }}>⏳ Chargement des données...</p>
        </div>
      </div>
    );
  }

  if (db.error) {
    return (
      <div className="home-page">
        <div className="stats-overview">
          <p style={{ textAlign: 'center', padding: '2rem', color: 'red' }}>❌ {db.error}</p>
          <p style={{ textAlign: 'center' }}>Assurez-vous que le serveur API est lancé: <code>npm run server</code></p>
        </div>
      </div>
    );
  }

  return (
    <div className="home-page">
      <div className="stats-overview">
        <div className="overview-header">
          <h1>📊 Dashboard SQDC</h1>
          <div className="time-range-selector">
            <button 
              className={`time-btn ${timeRange === 'today' ? 'active' : ''}`}
              onClick={() => setTimeRange('today')}
            >
              Aujourd'hui
            </button>
            <button 
              className={`time-btn ${timeRange === 'week' ? 'active' : ''}`}
              onClick={() => setTimeRange('week')}
            >
              Cette semaine
            </button>
            <button 
              className={`time-btn ${timeRange === 'last7' ? 'active' : ''}`}
              onClick={() => setTimeRange('last7')}
            >
              7 derniers jours
            </button>
            <button 
              className={`time-btn ${timeRange === 'month' ? 'active' : ''}`}
              onClick={() => setTimeRange('month')}
            >
              Ce mois
            </button>
            <button 
              className={`time-btn ${timeRange === 'year' ? 'active' : ''}`}
              onClick={() => setTimeRange('year')}
            >
              Cette année
            </button>
          </div>
        </div>

        {criticalAlerts.length > 0 && (
          <div className="alerts-block">
            <h3>🚨 Alertes ({criticalAlerts.length})</h3>
            <div className="alerts-list">
              {criticalAlerts.map(alert => (
                <div key={alert.id} className={`alert-item alert-${alert.status}`}>
                  <div className="alert-status">
                    {alert.status === 'critical' ? '🔴' : '⚠️'}
                  </div>
                  <div className="alert-info">
                    <div className="alert-name">{alert.name}</div>
                    <div className="alert-value">{alert.value} {alert.unit}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      <div className="main-grid">
        <div className="category-section">
          <div className="category-header">
            <h2>📊 Statistiques</h2>
          </div>
          <div className="stats-grid-inner">
            <div className="stat-card-inner">
              <div className="stat-number">{stats.total}</div>
              <div className="stat-label">KPI Total</div>
            </div>
            <div className="stat-card-inner">
              <div className="stat-number">{stats.good}</div>
              <div className="stat-label">✅ Bon</div>
            </div>
            <div className="stat-card-inner">
              <div className="stat-number">{stats.warning}</div>
              <div className="stat-label">⚠️ Attention</div>
            </div>
            <div className="stat-card-inner">
              <div className="stat-number">{stats.critical}</div>
              <div className="stat-label">🔴 Critique</div>
            </div>
            <div className="stat-card-inner">
              <div className="stat-number">{avgPerformance}%</div>
              <div className="stat-label">Performance</div>
            </div>
          </div>
        </div>

        {[1, 2, 3, 4, 5].map(catId => {
          const categoryKPIs = topKPIs[catId] || [];
          const category = db.categories.find(c => c.id === catId);
          
          if (!category) return null;

          return (
            <div key={catId} className="category-section">
              <div className="category-header">
                <h2 style={{ color: getCategoryColor(category.name) }}>
                  {category.emoji} {category.name}
                </h2>
              </div>
              <div className="kpi-grid">
                {categoryKPIs.map((kpi: any) => (
                  <KPICard
                    key={kpi.id}
                    kpi={kpi}
                    color={getCategoryColor(category.name)}
                  />
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};
