import React, { useState, useEffect, useCallback } from 'react';
import {
  Cpu,
  MemoryStick,
  HardDrive,
  Network,
  Activity,
  RefreshCw,
  Clock,
  Server,
  TrendingUp,
} from 'lucide-react';
import { getServerMetrics } from '../utils/api';

function formatBytes(bytes) {
  if (!bytes || bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'Ko', 'Mo', 'Go', 'To'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}

function formatUptime(seconds) {
  if (!seconds) return 'N/A';
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  if (days > 0) return `${days}j ${hours}h ${mins}m`;
  if (hours > 0) return `${hours}h ${mins}m`;
  return `${mins}m`;
}

function GaugeBar({ value, max = 100, color = 'primary', label, sublabel }) {
  const pct = Math.min(100, Math.round((value / max) * 100));
  const colorMap = {
    primary: { bar: 'bg-primary-500', text: 'text-primary-400', border: 'border-primary-500/30' },
    emerald: { bar: 'bg-emerald-500', text: 'text-emerald-400', border: 'border-emerald-500/30' },
    amber: { bar: 'bg-amber-500', text: 'text-amber-400', border: 'border-amber-500/30' },
    red: { bar: 'bg-red-500', text: 'text-red-400', border: 'border-red-500/30' },
  };
  const dangerColor = pct > 85 ? 'red' : pct > 65 ? 'amber' : color;
  const c = colorMap[dangerColor] || colorMap.primary;

  return (
    <div className={`card p-5 border ${c.border}`}>
      <div className="flex items-center justify-between mb-3">
        <span className="text-sm font-medium text-gray-300">{label}</span>
        <span className={`text-2xl font-bold ${c.text}`}>{pct}%</span>
      </div>
      <div className="w-full bg-dark-700 rounded-full h-3 mb-3 overflow-hidden">
        <div
          className={`h-3 rounded-full transition-all duration-700 ${c.bar}`}
          style={{ width: `${pct}%` }}
        />
      </div>
      <p className="text-xs text-gray-500">{sublabel}</p>
    </div>
  );
}

function MetricCard({ icon: Icon, label, value, sub, color = 'primary' }) {
  const colorMap = {
    primary: 'text-primary-400 bg-primary-500/10 border-primary-500/20',
    emerald: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20',
    amber: 'text-amber-400 bg-amber-500/10 border-amber-500/20',
    blue: 'text-blue-400 bg-blue-500/10 border-blue-500/20',
  };
  return (
    <div className={`card p-5 border ${colorMap[color]}`}>
      <div className="flex items-start gap-4">
        <div className={`p-3 rounded-xl border ${colorMap[color]}`}>
          <Icon className="w-6 h-6" />
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-xs text-gray-500 uppercase tracking-wider mb-1">{label}</p>
          <p className="text-xl font-bold text-white truncate">{value}</p>
          {sub && <p className="text-xs text-gray-500 mt-1">{sub}</p>}
        </div>
      </div>
    </div>
  );
}

export default function MonitoringPage() {
  const [metrics, setMetrics] = useState(null);
  const [loading, setLoading] = useState(true);
  const [lastUpdate, setLastUpdate] = useState(null);
  const [autoRefresh, setAutoRefresh] = useState(true);

  const fetchMetrics = useCallback(async () => {
    try {
      const res = await getServerMetrics();
      setMetrics(res.data);
      setLastUpdate(new Date());
    } catch (err) {
      console.error('Erreur métriques:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchMetrics();
  }, [fetchMetrics]);

  useEffect(() => {
    if (!autoRefresh) return;
    const interval = setInterval(fetchMetrics, 10000);
    return () => clearInterval(interval);
  }, [autoRefresh, fetchMetrics]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-white flex items-center gap-3">
            <Activity className="w-7 h-7 text-primary-400" />
            Monitoring Serveur
          </h2>
          <p className="text-gray-400 mt-1">
            Consommation des ressources en temps réel
          </p>
        </div>
        <div className="flex items-center gap-3">
          {lastUpdate && (
            <span className="text-xs text-gray-500 flex items-center gap-1">
              <Clock className="w-3.5 h-3.5" />
              Mis à jour : {lastUpdate.toLocaleTimeString('fr-FR')}
            </span>
          )}
          <button
            onClick={() => setAutoRefresh((v) => !v)}
            className={`btn-secondary text-sm flex items-center gap-2 ${autoRefresh ? 'text-emerald-400' : ''}`}
          >
            <Activity className="w-4 h-4" />
            {autoRefresh ? 'Auto (10s)' : 'Manuel'}
          </button>
          <button
            onClick={fetchMetrics}
            disabled={loading}
            className="btn-secondary flex items-center gap-2 text-sm"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            Rafraîchir
          </button>
        </div>
      </div>

      {loading && !metrics ? (
        <div className="card p-12 text-center">
          <RefreshCw className="w-8 h-8 text-primary-400 animate-spin mx-auto mb-3" />
          <p className="text-gray-400">Chargement des métriques...</p>
        </div>
      ) : metrics?.error ? (
        <div className="card p-8 text-center border border-red-500/20">
          <p className="text-red-400">Erreur : {metrics.error}</p>
        </div>
      ) : metrics ? (
        <>
          {/* Jauges principales */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <GaugeBar
              value={metrics.cpu?.usage || 0}
              label="Processeur (CPU)"
              sublabel={`Load avg: ${metrics.load?.load1?.toFixed(2)} / ${metrics.load?.load5?.toFixed(2)} / ${metrics.load?.load15?.toFixed(2)}`}
              color="primary"
            />
            <GaugeBar
              value={metrics.memory?.usagePercent || 0}
              label="Mémoire RAM"
              sublabel={`${formatBytes(metrics.memory?.used)} utilisés sur ${formatBytes(metrics.memory?.total)} — ${formatBytes(metrics.memory?.available)} disponibles`}
              color="emerald"
            />
            <GaugeBar
              value={metrics.disk?.usagePercent || 0}
              label="Espace Disque"
              sublabel={`${formatBytes(metrics.disk?.used)} utilisés sur ${formatBytes(metrics.disk?.total)} — ${formatBytes(metrics.disk?.free)} libres`}
              color="amber"
            />
          </div>

          {/* Métriques détaillées */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <MetricCard
              icon={Server}
              label="Uptime serveur"
              value={formatUptime(metrics.uptime)}
              sub="Depuis le dernier redémarrage"
              color="primary"
            />
            <MetricCard
              icon={TrendingUp}
              label="Charge système (1 min)"
              value={metrics.load?.load1?.toFixed(2) || 'N/A'}
              sub={`5 min: ${metrics.load?.load5?.toFixed(2)} — 15 min: ${metrics.load?.load15?.toFixed(2)}`}
              color="blue"
            />
            <MetricCard
              icon={Network}
              label="Réseau — Reçu"
              value={formatBytes(metrics.network?.rx)}
              sub="Total depuis le démarrage"
              color="emerald"
            />
            <MetricCard
              icon={Network}
              label="Réseau — Envoyé"
              value={formatBytes(metrics.network?.tx)}
              sub="Total depuis le démarrage"
              color="amber"
            />
          </div>

          {/* Tableau récapitulatif */}
          <div className="card overflow-hidden">
            <div className="px-6 py-4 border-b border-dark-700">
              <h3 className="text-base font-semibold text-white flex items-center gap-2">
                <HardDrive className="w-5 h-5 text-primary-400" />
                Récapitulatif des ressources
              </h3>
            </div>
            <div className="divide-y divide-dark-700">
              {[
                { label: 'CPU — Utilisation', value: `${metrics.cpu?.usage?.toFixed(1) || 0}%`, status: metrics.cpu?.usage > 85 ? 'critical' : metrics.cpu?.usage > 65 ? 'warning' : 'ok' },
                { label: 'RAM — Utilisée', value: `${formatBytes(metrics.memory?.used)} / ${formatBytes(metrics.memory?.total)}`, status: metrics.memory?.usagePercent > 85 ? 'critical' : metrics.memory?.usagePercent > 65 ? 'warning' : 'ok' },
                { label: 'RAM — Disponible', value: formatBytes(metrics.memory?.available), status: 'ok' },
                { label: 'Disque — Utilisé', value: `${formatBytes(metrics.disk?.used)} / ${formatBytes(metrics.disk?.total)}`, status: metrics.disk?.usagePercent > 85 ? 'critical' : metrics.disk?.usagePercent > 65 ? 'warning' : 'ok' },
                { label: 'Disque — Libre', value: formatBytes(metrics.disk?.free), status: 'ok' },
                { label: 'Réseau — Trafic entrant', value: formatBytes(metrics.network?.rx), status: 'ok' },
                { label: 'Réseau — Trafic sortant', value: formatBytes(metrics.network?.tx), status: 'ok' },
                { label: 'Uptime', value: formatUptime(metrics.uptime), status: 'ok' },
              ].map((row) => (
                <div key={row.label} className="px-6 py-3 flex items-center justify-between hover:bg-dark-800/50 transition-colors">
                  <span className="text-sm text-gray-400">{row.label}</span>
                  <div className="flex items-center gap-3">
                    <span className="text-sm font-medium text-white">{row.value}</span>
                    <span className={`w-2 h-2 rounded-full ${
                      row.status === 'critical' ? 'bg-red-400' :
                      row.status === 'warning' ? 'bg-amber-400' : 'bg-emerald-400'
                    }`} />
                  </div>
                </div>
              ))}
            </div>
          </div>
        </>
      ) : null}
    </div>
  );
}
