'use client';

import { useState, useEffect } from 'react';
import { 
  Database, 
  CreditCard, 
  Mail, 
  Key, 
  Cloud, 
  MessageSquare,
  AlertCircle,
  RefreshCw,
  Server,
  Activity,
  CheckCircle2,
  XCircle,
  HelpCircle
} from 'lucide-react';
import { apiFetch } from '@/lib/csrf/client';

interface SystemService {
  name: string;
  key: string;
  status: 'connected' | 'not_configured' | 'error';
  message?: string;
}

interface SystemInfo {
  services: SystemService[];
  environment: string;
  appUrl: string;
  activeSessions: number;
  uptime: number;
}

export default function AdminSystemPage() {
  const [info, setInfo] = useState<SystemInfo | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchSystemInfo = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const res = await apiFetch('/api/admin/system');
      if (!res.ok) throw new Error('Failed to fetch system info');
      const data = await res.json();
      setInfo(data);
    } catch (err: any) {
      setError(err.message || 'An error occurred');
    } finally {
      setIsLoading(false);
    }
  };

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

  if (isLoading) {
    return (
      <div className="space-y-6 animate-pulse">
        <div className="h-8 w-48 bg-slate-200 rounded"></div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {[...Array(6)].map((_, i) => (
            <div key={i} className="h-32 bg-white rounded-2xl border border-slate-200"></div>
          ))}
        </div>
      </div>
    );
  }

  if (error || !info) {
    return (
      <div className="p-6 bg-red-50 border border-red-200 rounded-2xl flex items-center justify-between text-red-700">
        <div className="flex items-center gap-3">
          <AlertCircle size={22} className="text-red-600" />
          <div>
            <h3 className="font-semibold text-red-900">Fehler beim Laden des System-Status</h3>
            <p className="text-xs text-red-600 mt-0.5">{error}</p>
          </div>
        </div>
        <button onClick={fetchSystemInfo} className="px-4 py-2 bg-red-600 text-white rounded-xl text-xs font-semibold hover:bg-red-700 transition-all shadow-xs">
          <RefreshCw size={14} className="inline mr-1.5" /> Erneut versuchen
        </button>
      </div>
    );
  }

  const getServiceIcon = (key: string) => {
    switch (key) {
      case 'postgres': return Database;
      case 'stripe': return CreditCard;
      case 'smtp': return Mail;
      case 'google_oauth': return Key;
      case 'r2': return Cloud;
      case 'discord': return MessageSquare;
      default: return Server;
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'connected': 
        return (
          <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200">
            <CheckCircle2 size={13} /> Verbunden
          </span>
        );
      case 'error': 
        return (
          <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-red-700 bg-red-50 px-2.5 py-1 rounded-full border border-red-200">
            <XCircle size={13} /> Fehler
          </span>
        );
      default: 
        return (
          <span className="inline-flex items-center gap-1.5 text-xs font-medium text-slate-500 bg-slate-100 px-2.5 py-1 rounded-full border border-slate-200">
            <HelpCircle size={13} /> Nicht konfiguriert
          </span>
        );
    }
  };

  const formatUptime = (seconds: number) => {
    const d = Math.floor(seconds / (3600 * 24));
    const h = Math.floor((seconds % (3600 * 24)) / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    if (d > 0) return `${d}d ${h}h`;
    if (h > 0) return `${h}h ${m}m`;
    return `${m}m`;
  };

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div className="flex items-center justify-between pb-2 border-b border-slate-200">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-slate-900 font-sans">
            System & Schnittstellen
          </h1>
          <p className="text-xs sm:text-sm text-slate-500 mt-1">
            Status aller externen APIs, Datenbanken und Services.
          </p>
        </div>
        <button onClick={fetchSystemInfo} className="p-2 text-slate-600 hover:text-slate-900 bg-white border border-slate-200 rounded-xl transition-colors shadow-xs">
          <RefreshCw size={16} className={isLoading ? "animate-spin" : ""} />
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {info.services.map((service, i) => {
          const Icon = getServiceIcon(service.key);
          return (
            <div key={i} className="bg-white border border-slate-200 rounded-2xl p-5 flex flex-col justify-between shadow-xs">
              <div className="flex items-center justify-between gap-3 mb-4">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-slate-50 rounded-xl border border-slate-200 text-slate-700">
                    <Icon size={20} />
                  </div>
                  <h3 className="font-bold text-slate-900">{service.name}</h3>
                </div>
                {getStatusBadge(service.status)}
              </div>
              
              {service.message && (
                <p className="text-xs text-slate-500 mt-2 font-mono bg-slate-50 p-2 rounded-lg border border-slate-100 truncate" title={service.message}>
                  {service.message}
                </p>
              )}
            </div>
          );
        })}
      </div>

      <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-xs">
        <h3 className="text-sm font-bold text-slate-900 mb-6 flex items-center gap-2">
          <Activity size={18} className="text-slate-600" />
          Laufzeit & Umgebung
        </h3>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          <div className="space-y-4">
            <div>
              <p className="text-xs text-slate-500 mb-1 font-mono uppercase tracking-wider">Modus / Environment</p>
              <div className="flex items-center gap-2">
                <span className={`px-2.5 py-0.5 rounded text-xs font-mono font-bold border
                  ${info.environment === 'production' 
                    ? 'bg-emerald-50 text-emerald-800 border-emerald-200' 
                    : 'bg-amber-50 text-amber-800 border-amber-200'}`}
                >
                  {info.environment.toUpperCase()}
                </span>
              </div>
            </div>
            
            <div>
              <p className="text-xs text-slate-500 mb-1 font-mono uppercase tracking-wider">App URL</p>
              <p className="text-xs font-mono text-slate-800 bg-slate-50 px-3 py-1.5 rounded-lg border border-slate-200 inline-block font-semibold">
                {info.appUrl || 'Not configured'}
              </p>
            </div>
          </div>
          
          <div className="space-y-4">
            <div>
              <p className="text-xs text-slate-500 mb-1 font-mono uppercase tracking-wider">Aktive Sitzungen</p>
              <p className="text-2xl font-mono text-slate-900 font-bold">
                {info.activeSessions.toLocaleString('de-DE')}
              </p>
            </div>
            
            <div>
              <p className="text-xs text-slate-500 mb-1 font-mono uppercase tracking-wider">Prozess-Uptime</p>
              <p className="text-sm font-mono text-slate-800 font-semibold">
                {formatUptime(info.uptime)}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
