'use client';

import { useState, useEffect } from 'react';

// Types
interface ServiceModule {
  id: string;
  name: string;
  display_name: string;
  description: string | null;
  service_type: string;
  port: number | null;
  technology_stack: string[];
  repository_path: string | null;
  docker_image: string | null;
  data_categories: string[];
  processes_pii: boolean;
  processes_health_data: boolean;
  ai_components: boolean;
  criticality: string;
  owner_team: string | null;
  is_active: boolean;
  compliance_score: number | null;
  regulation_count: number;
  risk_count: number;
  created_at: string;
  regulations?: Array<{
    code: string;
    name: string;
    relevance_level: string;
    notes: string | null;
  }>;
}

interface ModulesOverview {
  total_modules: number;
  modules_by_type: Record<string, number>;
  modules_by_criticality: Record<string, number>;
  modules_processing_pii: number;
  modules_with_ai: number;
  average_compliance_score: number | null;
  regulations_coverage: Record<string, number>;
}

// Service Type Icons and Colors
const SERVICE_TYPE_CONFIG: Record<string, { icon: string; color: string; bgColor: string }> = {
  backend: { icon: '⚙️', color: 'text-blue-700', bgColor: 'bg-blue-100' },
  database: { icon: '🗄️', color: 'text-purple-700', bgColor: 'bg-purple-100' },
  ai: { icon: '🤖', color: 'text-pink-700', bgColor: 'bg-pink-100' },
  communication: { icon: '💬', color: 'text-green-700', bgColor: 'bg-green-100' },
  storage: { icon: '📦', color: 'text-orange-700', bgColor: 'bg-orange-100' },
  infrastructure: { icon: '🌐', color: 'text-gray-700', bgColor: 'bg-gray-100' },
  monitoring: { icon: '📊', color: 'text-cyan-700', bgColor: 'bg-cyan-100' },
  security: { icon: '🔒', color: 'text-red-700', bgColor: 'bg-red-100' },
};

const CRITICALITY_CONFIG: Record<string, { color: string; bgColor: string }> = {
  critical: { color: 'text-red-700', bgColor: 'bg-red-100' },
  high: { color: 'text-orange-700', bgColor: 'bg-orange-100' },
  medium: { color: 'text-yellow-700', bgColor: 'bg-yellow-100' },
  low: { color: 'text-green-700', bgColor: 'bg-green-100' },
};

const RELEVANCE_CONFIG: Record<string, { color: string; bgColor: string }> = {
  critical: { color: 'text-red-700', bgColor: 'bg-red-100' },
  high: { color: 'text-orange-700', bgColor: 'bg-orange-100' },
  medium: { color: 'text-yellow-700', bgColor: 'bg-yellow-100' },
  low: { color: 'text-green-700', bgColor: 'bg-green-100' },
};

export default function ModulesPage() {
  const [modules, setModules] = useState<ServiceModule[]>([]);
  const [overview, setOverview] = useState<ModulesOverview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Filters
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [criticalityFilter, setCriticalityFilter] = useState<string>('all');
  const [piiFilter, setPiiFilter] = useState<boolean | null>(null);
  const [aiFilter, setAiFilter] = useState<boolean | null>(null);
  const [searchTerm, setSearchTerm] = useState('');

  // Selected module for detail view
  const [selectedModule, setSelectedModule] = useState<ServiceModule | null>(null);
  const [loadingDetail, setLoadingDetail] = useState(false);

  // AI Risk Assessment
  const [riskAssessment, setRiskAssessment] = useState<{
    overall_risk: string;
    risk_factors: Array<{ factor: string; severity: string; likelihood: string }>;
    recommendations: string[];
    compliance_gaps: string[];
    confidence_score: number;
  } | null>(null);
  const [loadingRisk, setLoadingRisk] = useState(false);
  const [showRiskPanel, setShowRiskPanel] = useState(false);

  const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000';
  const API_BASE = `${BACKEND_URL}/api/v1/compliance`;

  useEffect(() => {
    fetchModules();
    fetchOverview();
  }, []);

  const fetchModules = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams();
      if (typeFilter !== 'all') params.append('service_type', typeFilter);
      if (criticalityFilter !== 'all') params.append('criticality', criticalityFilter);
      if (piiFilter !== null) params.append('processes_pii', String(piiFilter));
      if (aiFilter !== null) params.append('ai_components', String(aiFilter));

      const url = `${API_BASE}/modules${params.toString() ? '?' + params.toString() : ''}`;
      const res = await fetch(url);
      if (!res.ok) throw new Error('Failed to fetch modules');
      const data = await res.json();
      setModules(data.modules || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  const fetchOverview = async () => {
    try {
      const res = await fetch(`${API_BASE}/modules/overview`);
      if (!res.ok) throw new Error('Failed to fetch overview');
      const data = await res.json();
      setOverview(data);
    } catch (err) {
      console.error('Failed to fetch overview:', err);
    }
  };

  const fetchModuleDetail = async (moduleId: string) => {
    try {
      setLoadingDetail(true);
      const res = await fetch(`${API_BASE}/modules/${moduleId}`);
      if (!res.ok) throw new Error('Failed to fetch module details');
      const data = await res.json();
      setSelectedModule(data);
    } catch (err) {
      console.error('Failed to fetch module details:', err);
    } finally {
      setLoadingDetail(false);
    }
  };

  const seedModules = async (force: boolean = false) => {
    try {
      const res = await fetch(`${API_BASE}/modules/seed`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ force }),
      });
      if (!res.ok) throw new Error('Failed to seed modules');
      const data = await res.json();
      alert(`Seeded ${data.modules_created} modules with ${data.mappings_created} regulation mappings`);
      fetchModules();
      fetchOverview();
    } catch (err) {
      alert('Failed to seed modules: ' + (err instanceof Error ? err.message : 'Unknown error'));
    }
  };

  const assessModuleRisk = async (moduleId: string) => {
    setLoadingRisk(true);
    setShowRiskPanel(true);
    setRiskAssessment(null);
    try {
      const res = await fetch(`${API_BASE}/ai/assess-risk`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ module_id: moduleId }),
      });
      if (res.ok) {
        const data = await res.json();
        setRiskAssessment(data);
      } else {
        alert('AI-Risikobewertung fehlgeschlagen');
      }
    } catch (err) {
      alert('Netzwerkfehler bei AI-Risikobewertung');
    } finally {
      setLoadingRisk(false);
    }
  };

  // Filter modules by search term
  const filteredModules = modules.filter(m => {
    if (!searchTerm) return true;
    const term = searchTerm.toLowerCase();
    return (
      m.name.toLowerCase().includes(term) ||
      m.display_name.toLowerCase().includes(term) ||
      (m.description && m.description.toLowerCase().includes(term)) ||
      m.technology_stack.some(t => t.toLowerCase().includes(term))
    );
  });

  // Group by type for visualization
  const modulesByType = filteredModules.reduce((acc, m) => {
    const type = m.service_type || 'unknown';
    if (!acc[type]) acc[type] = [];
    acc[type].push(m);
    return acc;
  }, {} as Record<string, ServiceModule[]>);

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Service Module Registry</h1>
          <p className="text-gray-600 mt-1">
            Alle {overview?.total_modules || 0} Breakpilot-Services mit Regulation-Mappings
          </p>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => seedModules(false)}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
          >
            Seed Modules
          </button>
          <button
            onClick={() => seedModules(true)}
            className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition"
          >
            Force Re-Seed
          </button>
        </div>
      </div>

      {/* Overview Stats */}
      {overview && (
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-3xl font-bold text-blue-600">{overview.total_modules}</div>
            <div className="text-sm text-gray-600">Services</div>
          </div>
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-3xl font-bold text-red-600">{overview.modules_by_criticality?.critical || 0}</div>
            <div className="text-sm text-gray-600">Critical</div>
          </div>
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-3xl font-bold text-purple-600">{overview.modules_processing_pii}</div>
            <div className="text-sm text-gray-600">PII-Processing</div>
          </div>
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-3xl font-bold text-pink-600">{overview.modules_with_ai}</div>
            <div className="text-sm text-gray-600">AI-Komponenten</div>
          </div>
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-3xl font-bold text-green-600">
              {Object.keys(overview.regulations_coverage || {}).length}
            </div>
            <div className="text-sm text-gray-600">Regulations</div>
          </div>
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-3xl font-bold text-cyan-600">
              {overview.average_compliance_score !== null
                ? `${overview.average_compliance_score}%`
                : 'N/A'}
            </div>
            <div className="text-sm text-gray-600">Avg. Score</div>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="bg-white rounded-lg p-4 shadow border">
        <div className="flex flex-wrap gap-4 items-center">
          <div>
            <label className="block text-xs text-gray-500 mb-1">Service Type</label>
            <select
              value={typeFilter}
              onChange={(e) => { setTypeFilter(e.target.value); }}
              className="border rounded px-3 py-2 text-sm"
            >
              <option value="all">Alle Typen</option>
              <option value="backend">Backend</option>
              <option value="database">Database</option>
              <option value="ai">AI/ML</option>
              <option value="communication">Communication</option>
              <option value="storage">Storage</option>
              <option value="infrastructure">Infrastructure</option>
              <option value="monitoring">Monitoring</option>
              <option value="security">Security</option>
            </select>
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">Criticality</label>
            <select
              value={criticalityFilter}
              onChange={(e) => { setCriticalityFilter(e.target.value); }}
              className="border rounded px-3 py-2 text-sm"
            >
              <option value="all">Alle</option>
              <option value="critical">Critical</option>
              <option value="high">High</option>
              <option value="medium">Medium</option>
              <option value="low">Low</option>
            </select>
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">PII</label>
            <select
              value={piiFilter === null ? 'all' : String(piiFilter)}
              onChange={(e) => {
                const val = e.target.value;
                setPiiFilter(val === 'all' ? null : val === 'true');
              }}
              className="border rounded px-3 py-2 text-sm"
            >
              <option value="all">Alle</option>
              <option value="true">Verarbeitet PII</option>
              <option value="false">Keine PII</option>
            </select>
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">AI</label>
            <select
              value={aiFilter === null ? 'all' : String(aiFilter)}
              onChange={(e) => {
                const val = e.target.value;
                setAiFilter(val === 'all' ? null : val === 'true');
              }}
              className="border rounded px-3 py-2 text-sm"
            >
              <option value="all">Alle</option>
              <option value="true">Mit AI</option>
              <option value="false">Ohne AI</option>
            </select>
          </div>
          <div className="flex-1">
            <label className="block text-xs text-gray-500 mb-1">Suche</label>
            <input
              type="text"
              placeholder="Service, Beschreibung, Technologie..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="border rounded px-3 py-2 text-sm w-full"
            />
          </div>
          <div className="pt-5">
            <button
              onClick={fetchModules}
              className="px-4 py-2 bg-gray-100 rounded hover:bg-gray-200 transition text-sm"
            >
              Filter anwenden
            </button>
          </div>
        </div>
      </div>

      {/* Error */}
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 p-4 rounded-lg">
          {error}
        </div>
      )}

      {/* Loading */}
      {loading && (
        <div className="text-center py-12 text-gray-500">
          Lade Module...
        </div>
      )}

      {/* Main Content - Two Column Layout */}
      {!loading && (
        <div className="flex gap-6">
          {/* Module List */}
          <div className="flex-1 space-y-4">
            {Object.entries(modulesByType).map(([type, typeModules]) => (
              <div key={type} className="bg-white rounded-lg shadow border">
                <div className={`px-4 py-2 border-b ${SERVICE_TYPE_CONFIG[type]?.bgColor || 'bg-gray-100'}`}>
                  <span className="text-lg mr-2">{SERVICE_TYPE_CONFIG[type]?.icon || '📁'}</span>
                  <span className={`font-semibold ${SERVICE_TYPE_CONFIG[type]?.color || 'text-gray-700'}`}>
                    {type.charAt(0).toUpperCase() + type.slice(1)}
                  </span>
                  <span className="text-gray-500 ml-2">({typeModules.length})</span>
                </div>
                <div className="divide-y">
                  {typeModules.map((module) => (
                    <div
                      key={module.id}
                      onClick={() => fetchModuleDetail(module.name)}
                      className={`p-4 cursor-pointer hover:bg-gray-50 transition ${
                        selectedModule?.id === module.id ? 'bg-blue-50' : ''
                      }`}
                    >
                      <div className="flex justify-between items-start">
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <span className="font-medium text-gray-900">{module.display_name}</span>
                            {module.port && (
                              <span className="text-xs text-gray-400">:{module.port}</span>
                            )}
                          </div>
                          <div className="text-sm text-gray-500 mt-1">{module.name}</div>
                          {module.description && (
                            <div className="text-sm text-gray-600 mt-1 line-clamp-2">
                              {module.description}
                            </div>
                          )}
                          <div className="flex flex-wrap gap-1 mt-2">
                            {module.technology_stack.slice(0, 4).map((tech, i) => (
                              <span key={i} className="px-2 py-0.5 bg-gray-100 text-gray-600 text-xs rounded">
                                {tech}
                              </span>
                            ))}
                            {module.technology_stack.length > 4 && (
                              <span className="px-2 py-0.5 text-gray-400 text-xs">
                                +{module.technology_stack.length - 4}
                              </span>
                            )}
                          </div>
                        </div>
                        <div className="flex flex-col items-end gap-1">
                          <span className={`px-2 py-0.5 text-xs rounded ${
                            CRITICALITY_CONFIG[module.criticality]?.bgColor || 'bg-gray-100'
                          } ${CRITICALITY_CONFIG[module.criticality]?.color || 'text-gray-700'}`}>
                            {module.criticality}
                          </span>
                          <div className="flex gap-1 mt-1">
                            {module.processes_pii && (
                              <span className="px-1.5 py-0.5 bg-purple-100 text-purple-700 text-xs rounded" title="Verarbeitet PII">
                                PII
                              </span>
                            )}
                            {module.ai_components && (
                              <span className="px-1.5 py-0.5 bg-pink-100 text-pink-700 text-xs rounded" title="AI-Komponenten">
                                AI
                              </span>
                            )}
                          </div>
                          <div className="text-xs text-gray-400 mt-1">
                            {module.regulation_count} Regulations
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}

            {filteredModules.length === 0 && !loading && (
              <div className="text-center py-12 text-gray-500 bg-white rounded-lg shadow border">
                Keine Module gefunden.
                <button
                  onClick={() => seedModules(false)}
                  className="text-blue-600 hover:underline ml-1"
                >
                  Jetzt seeden?
                </button>
              </div>
            )}
          </div>

          {/* Detail Panel */}
          {selectedModule && (
            <div className="w-96 bg-white rounded-lg shadow border sticky top-6 h-fit">
              <div className={`px-4 py-3 border-b ${SERVICE_TYPE_CONFIG[selectedModule.service_type]?.bgColor || 'bg-gray-100'}`}>
                <div className="flex items-center justify-between">
                  <span className="text-lg">{SERVICE_TYPE_CONFIG[selectedModule.service_type]?.icon || '📁'}</span>
                  <button
                    onClick={() => setSelectedModule(null)}
                    className="text-gray-400 hover:text-gray-600"
                  >
                    ✕
                  </button>
                </div>
                <h3 className="font-bold text-lg mt-2">{selectedModule.display_name}</h3>
                <div className="text-sm text-gray-600">{selectedModule.name}</div>
              </div>

              {loadingDetail ? (
                <div className="p-4 text-center text-gray-500">Lade Details...</div>
              ) : (
                <div className="p-4 space-y-4">
                  {/* Description */}
                  {selectedModule.description && (
                    <div>
                      <div className="text-xs text-gray-500 uppercase mb-1">Beschreibung</div>
                      <div className="text-sm text-gray-700">{selectedModule.description}</div>
                    </div>
                  )}

                  {/* Technical Details */}
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    {selectedModule.port && (
                      <div>
                        <span className="text-gray-500">Port:</span>
                        <span className="ml-1 font-mono">{selectedModule.port}</span>
                      </div>
                    )}
                    <div>
                      <span className="text-gray-500">Criticality:</span>
                      <span className={`ml-1 px-1.5 py-0.5 rounded text-xs ${
                        CRITICALITY_CONFIG[selectedModule.criticality]?.bgColor || ''
                      } ${CRITICALITY_CONFIG[selectedModule.criticality]?.color || ''}`}>
                        {selectedModule.criticality}
                      </span>
                    </div>
                  </div>

                  {/* Technology Stack */}
                  <div>
                    <div className="text-xs text-gray-500 uppercase mb-1">Tech Stack</div>
                    <div className="flex flex-wrap gap-1">
                      {selectedModule.technology_stack.map((tech, i) => (
                        <span key={i} className="px-2 py-0.5 bg-gray-100 text-gray-700 text-xs rounded">
                          {tech}
                        </span>
                      ))}
                    </div>
                  </div>

                  {/* Data Categories */}
                  {selectedModule.data_categories.length > 0 && (
                    <div>
                      <div className="text-xs text-gray-500 uppercase mb-1">Daten-Kategorien</div>
                      <div className="flex flex-wrap gap-1">
                        {selectedModule.data_categories.map((cat, i) => (
                          <span key={i} className="px-2 py-0.5 bg-blue-50 text-blue-700 text-xs rounded">
                            {cat}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Flags */}
                  <div className="flex flex-wrap gap-2">
                    {selectedModule.processes_pii && (
                      <span className="px-2 py-1 bg-purple-100 text-purple-700 text-xs rounded">
                        Verarbeitet PII
                      </span>
                    )}
                    {selectedModule.ai_components && (
                      <span className="px-2 py-1 bg-pink-100 text-pink-700 text-xs rounded">
                        AI-Komponenten
                      </span>
                    )}
                    {selectedModule.processes_health_data && (
                      <span className="px-2 py-1 bg-red-100 text-red-700 text-xs rounded">
                        Gesundheitsdaten
                      </span>
                    )}
                  </div>

                  {/* Regulations */}
                  {selectedModule.regulations && selectedModule.regulations.length > 0 && (
                    <div>
                      <div className="text-xs text-gray-500 uppercase mb-2">
                        Applicable Regulations ({selectedModule.regulations.length})
                      </div>
                      <div className="space-y-2">
                        {selectedModule.regulations.map((reg, i) => (
                          <div key={i} className="p-2 bg-gray-50 rounded text-sm">
                            <div className="flex justify-between items-start">
                              <span className="font-medium">{reg.code}</span>
                              <span className={`px-1.5 py-0.5 rounded text-xs ${
                                RELEVANCE_CONFIG[reg.relevance_level]?.bgColor || 'bg-gray-100'
                              } ${RELEVANCE_CONFIG[reg.relevance_level]?.color || 'text-gray-700'}`}>
                                {reg.relevance_level}
                              </span>
                            </div>
                            <div className="text-gray-500 text-xs">{reg.name}</div>
                            {reg.notes && (
                              <div className="text-gray-600 text-xs mt-1 italic">{reg.notes}</div>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Owner */}
                  {selectedModule.owner_team && (
                    <div>
                      <div className="text-xs text-gray-500 uppercase mb-1">Owner</div>
                      <div className="text-sm text-gray-700">{selectedModule.owner_team}</div>
                    </div>
                  )}

                  {/* Repository */}
                  {selectedModule.repository_path && (
                    <div>
                      <div className="text-xs text-gray-500 uppercase mb-1">Repository</div>
                      <code className="text-xs bg-gray-100 px-2 py-1 rounded block">
                        {selectedModule.repository_path}
                      </code>
                    </div>
                  )}

                  {/* AI Risk Assessment Button */}
                  <div className="pt-2 border-t">
                    <button
                      onClick={() => assessModuleRisk(selectedModule.id)}
                      disabled={loadingRisk}
                      className="w-full px-4 py-2 bg-gradient-to-r from-purple-600 to-pink-600 text-white rounded-lg hover:from-purple-700 hover:to-pink-700 transition disabled:opacity-50 flex items-center justify-center gap-2"
                    >
                      {loadingRisk ? (
                        <>
                          <span className="animate-spin">⚙️</span>
                          AI analysiert...
                        </>
                      ) : (
                        <>
                          <span>🤖</span>
                          AI Risikobewertung
                        </>
                      )}
                    </button>
                  </div>

                  {/* AI Risk Assessment Panel */}
                  {showRiskPanel && (
                    <div className="mt-4 p-4 bg-gradient-to-br from-purple-50 to-pink-50 rounded-lg border border-purple-200">
                      <div className="flex justify-between items-center mb-3">
                        <h4 className="font-semibold text-purple-900 flex items-center gap-2">
                          <span>🤖</span> AI Risikobewertung
                        </h4>
                        <button
                          onClick={() => setShowRiskPanel(false)}
                          className="text-purple-400 hover:text-purple-600"
                        >
                          ✕
                        </button>
                      </div>

                      {loadingRisk ? (
                        <div className="text-center py-4 text-purple-600">
                          <div className="animate-pulse">Analysiere Compliance-Risiken...</div>
                        </div>
                      ) : riskAssessment ? (
                        <div className="space-y-3">
                          {/* Overall Risk */}
                          <div className="flex items-center gap-2">
                            <span className="text-sm text-gray-600">Gesamtrisiko:</span>
                            <span className={`px-2 py-1 rounded text-sm font-medium ${
                              riskAssessment.overall_risk === 'critical' ? 'bg-red-100 text-red-700' :
                              riskAssessment.overall_risk === 'high' ? 'bg-orange-100 text-orange-700' :
                              riskAssessment.overall_risk === 'medium' ? 'bg-yellow-100 text-yellow-700' :
                              'bg-green-100 text-green-700'
                            }`}>
                              {riskAssessment.overall_risk.toUpperCase()}
                            </span>
                            <span className="text-xs text-gray-400">
                              ({Math.round(riskAssessment.confidence_score * 100)}% Konfidenz)
                            </span>
                          </div>

                          {/* Risk Factors */}
                          {riskAssessment.risk_factors.length > 0 && (
                            <div>
                              <div className="text-xs text-gray-500 uppercase mb-1">Risikofaktoren</div>
                              <div className="space-y-1">
                                {riskAssessment.risk_factors.map((factor, i) => (
                                  <div key={i} className="flex items-center justify-between text-sm bg-white/50 rounded px-2 py-1">
                                    <span className="text-gray-700">{factor.factor}</span>
                                    <span className={`text-xs px-1.5 py-0.5 rounded ${
                                      factor.severity === 'critical' || factor.severity === 'high'
                                        ? 'bg-red-100 text-red-600'
                                        : 'bg-yellow-100 text-yellow-600'
                                    }`}>
                                      {factor.severity}
                                    </span>
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}

                          {/* Compliance Gaps */}
                          {riskAssessment.compliance_gaps.length > 0 && (
                            <div>
                              <div className="text-xs text-gray-500 uppercase mb-1">Compliance-Lücken</div>
                              <ul className="text-sm text-gray-700 space-y-1">
                                {riskAssessment.compliance_gaps.map((gap, i) => (
                                  <li key={i} className="flex items-start gap-1">
                                    <span className="text-red-500">⚠</span>
                                    <span>{gap}</span>
                                  </li>
                                ))}
                              </ul>
                            </div>
                          )}

                          {/* Recommendations */}
                          {riskAssessment.recommendations.length > 0 && (
                            <div>
                              <div className="text-xs text-gray-500 uppercase mb-1">Empfehlungen</div>
                              <ul className="text-sm text-gray-700 space-y-1">
                                {riskAssessment.recommendations.map((rec, i) => (
                                  <li key={i} className="flex items-start gap-1">
                                    <span className="text-green-500">→</span>
                                    <span>{rec}</span>
                                  </li>
                                ))}
                              </ul>
                            </div>
                          )}
                        </div>
                      ) : (
                        <div className="text-center py-4 text-gray-500 text-sm">
                          Klicken Sie auf &quot;AI Risikobewertung&quot; um eine Analyse zu starten.
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* Regulations Coverage Overview */}
      {overview && overview.regulations_coverage && Object.keys(overview.regulations_coverage).length > 0 && (
        <div className="bg-white rounded-lg shadow border p-4">
          <h3 className="font-semibold text-gray-900 mb-4">Regulation Coverage</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
            {Object.entries(overview.regulations_coverage)
              .sort(([, a], [, b]) => b - a)
              .map(([code, count]) => (
                <div key={code} className="bg-gray-50 rounded p-3 text-center">
                  <div className="text-2xl font-bold text-blue-600">{count}</div>
                  <div className="text-xs text-gray-600 truncate" title={code}>{code}</div>
                </div>
              ))}
          </div>
        </div>
      )}
    </div>
  );
}
