import React, { useState, useEffect } from 'react';
import {
  Activity,
  Box,
  Container,
  Server,
  Clock,
  TrendingUp,
  AlertCircle,
  CheckCircle2,
  XCircle,
} from 'lucide-react';
import { getApps, getSystemInfo } from '../utils/api';
import StatusBadge from '../components/StatusBadge';

function StatCard({ icon: Icon, label, value, color, subtext }) {
  return (
    <div className="card p-5">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm text-gray-400">{label}</p>
          <p className="text-2xl font-bold text-white mt-1">{value}</p>
          {subtext && <p className="text-xs text-gray-500 mt-1">{subtext}</p>}
        </div>
        <div
          className={`w-12 h-12 rounded-xl flex items-center justify-center ${color}`}
        >
          <Icon className="w-6 h-6 text-white" />
        </div>
      </div>
    </div>
  );
}

export default function DashboardPage({ apps }) {
  const [systemInfo, setSystemInfo] = useState(null);

  useEffect(() => {
    getSystemInfo()
      .then((res) => setSystemInfo(res.data))
      .catch(console.error);
  }, []);

  const onlineApps = apps.filter((a) => a.status === 'online').length;
  const offlineApps = apps.filter((a) => a.status === 'offline').length;
  const errorApps = apps.filter((a) => a.status === 'error').length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-2xl font-bold text-white">Tableau de bord</h2>
        <p className="text-gray-400 mt-1">
          Vue d'ensemble de l'infrastructure Manus
        </p>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          icon={Box}
          label="Applications"
          value={apps.length}
          color="bg-primary-600"
          subtext="Applications déployées"
        />
        <StatCard
          icon={CheckCircle2}
          label="En ligne"
          value={onlineApps}
          color="bg-emerald-600"
          subtext="Applications fonctionnelles"
        />
        <StatCard
          icon={XCircle}
          label="Hors ligne"
          value={offlineApps}
          color="bg-gray-600"
          subtext="Applications arrêtées"
        />
        <StatCard
          icon={AlertCircle}
          label="Erreurs"
          value={errorApps}
          color="bg-red-600"
          subtext="Applications en erreur"
        />
      </div>

      {/* System Info + Apps Overview */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* System Info */}
        <div className="card p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <Server className="w-5 h-5 text-primary-400" />
            Informations système
          </h3>
          <div className="space-y-3">
            <div className="flex items-center justify-between py-2 border-b border-dark-700">
              <span className="text-sm text-gray-400">Serveur</span>
              <span className="text-sm text-gray-200">
                78.138.58.109 (Recette)
              </span>
            </div>
            <div className="flex items-center justify-between py-2 border-b border-dark-700">
              <span className="text-sm text-gray-400">Conteneurs actifs</span>
              <span className="text-sm text-gray-200">
                {systemInfo?.runningContainers || '...'} /{' '}
                {systemInfo?.totalContainers || '...'}
              </span>
            </div>
            <div className="flex items-center justify-between py-2 border-b border-dark-700">
              <span className="text-sm text-gray-400">Gitea</span>
              <a
                href="https://git.recette.santinova-soft.org"
                target="_blank"
                rel="noopener noreferrer"
                className="text-sm text-primary-400 hover:text-primary-300"
              >
                git.recette.santinova-soft.org
              </a>
            </div>
            <div className="flex items-center justify-between py-2 border-b border-dark-700">
              <span className="text-sm text-gray-400">Reverse Proxy</span>
              <span className="text-sm text-gray-200">
                Traefik + Let's Encrypt
              </span>
            </div>
            <div className="flex items-center justify-between py-2">
              <span className="text-sm text-gray-400">Heure serveur</span>
              <span className="text-sm text-gray-200">
                {systemInfo?.serverTime
                  ? new Date(systemInfo.serverTime).toLocaleString('fr-FR')
                  : '...'}
              </span>
            </div>
          </div>
        </div>

        {/* Apps Quick View */}
        <div className="card p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <Activity className="w-5 h-5 text-primary-400" />
            État des applications
          </h3>
          {apps.length === 0 ? (
            <p className="text-gray-500 text-sm">Aucune application détectée</p>
          ) : (
            <div className="space-y-3">
              {apps.map((app) => (
                <div
                  key={app.id}
                  className="flex items-center justify-between py-3 px-4 rounded-lg bg-dark-700/50 border border-dark-600/50"
                >
                  <div className="flex items-center gap-3">
                    <div
                      className={`w-3 h-3 rounded-full ${
                        app.status === 'online'
                          ? 'bg-emerald-400 animate-pulse-dot'
                          : app.status === 'error'
                          ? 'bg-red-400'
                          : 'bg-gray-500'
                      }`}
                    />
                    <div>
                      <p className="text-sm font-medium text-gray-200">
                        {app.name}
                      </p>
                      <p className="text-xs text-gray-500">
                        {app.containerName}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    {app.health?.recette?.responseTime && (
                      <span className="text-xs text-gray-500">
                        {app.health.recette.responseTime}ms
                      </span>
                    )}
                    <StatusBadge status={app.status} />
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
