'use client'

/**
 * Service Module Registry Page
 *
 * Features:
 * - List all Breakpilot services with regulation mappings
 * - Filter by type, criticality, PII, AI
 * - Detail panel with regulations
 * - Seed functionality
 */

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { PagePurpose } from '@/components/common/PagePurpose'

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>
}

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-slate-700', bgColor: 'bg-slate-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)

  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('')

  const [selectedModule, setSelectedModule] = useState<ServiceModule | null>(null)
  const [loadingDetail, setLoadingDetail] = useState(false)

  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/admin/compliance/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/admin/compliance/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/admin/compliance/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/admin/compliance/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 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))
    )
  })

  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="min-h-screen bg-slate-50 p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Service Module Registry</h1>
          <p className="text-slate-600">
            Alle {overview?.total_modules || 0} Breakpilot-Services mit Regulation-Mappings
          </p>
        </div>
        <Link
          href="/compliance/hub"
          className="flex items-center gap-2 text-slate-600 hover:text-slate-800"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          Compliance Hub
        </Link>
      </div>

      {/* Page Purpose */}
      <PagePurpose
        title="Service Module Registry"
        purpose="Das Service Registry dokumentiert alle Breakpilot-Microservices und deren regulatorische Anforderungen. Jeder Service wird mit relevanten Regulierungen (DSGVO, AI Act, BSI TR-03161) verknuepft und zeigt an, welche Compliance-Anforderungen gelten."
        audience={['Entwickler', 'CISO', 'Compliance Officer', 'Architekten']}
        gdprArticles={['Art. 30 (Verzeichnis)', 'Art. 32 (Sicherheit)']}
        architecture={{
          services: ['Python Backend (FastAPI)', 'compliance_modules Modul'],
          databases: ['PostgreSQL (service_modules, module_regulation_mappings Tables)'],
        }}
        relatedPages={[
          { name: 'Controls', href: '/compliance/controls', description: 'Massnahmen verwalten' },
          { name: 'Risks', href: '/compliance/risks', description: 'Risikomatrix' },
        ]}
      />

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

      {/* Filters */}
      <div className="bg-white rounded-xl shadow-sm border p-4 mb-6">
        <div className="flex flex-wrap gap-4 items-end">
          <div>
            <label className="block text-xs text-slate-500 mb-1">Service Type</label>
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
              className="border rounded-lg 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-slate-500 mb-1">Criticality</label>
            <select
              value={criticalityFilter}
              onChange={(e) => setCriticalityFilter(e.target.value)}
              className="border rounded-lg 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-slate-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-lg 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-slate-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-lg 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 min-w-[200px]">
            <label className="block text-xs text-slate-500 mb-1">Suche</label>
            <input
              type="text"
              placeholder="Service, Beschreibung, Technologie..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="border rounded-lg px-3 py-2 text-sm w-full"
            />
          </div>
          <button
            onClick={fetchModules}
            className="px-4 py-2 bg-slate-100 rounded-lg hover:bg-slate-200 text-sm"
          >
            Filter
          </button>
          <button
            onClick={() => seedModules(false)}
            className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 text-sm"
          >
            Seed
          </button>
        </div>
      </div>

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

      {/* Main Content */}
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600" />
        </div>
      ) : (
        <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-xl shadow-sm border overflow-hidden">
                <div className={`px-4 py-2 border-b ${SERVICE_TYPE_CONFIG[type]?.bgColor || 'bg-slate-100'}`}>
                  <span className="text-lg mr-2">{SERVICE_TYPE_CONFIG[type]?.icon || '📁'}</span>
                  <span className={`font-semibold ${SERVICE_TYPE_CONFIG[type]?.color || 'text-slate-700'}`}>
                    {type.charAt(0).toUpperCase() + type.slice(1)}
                  </span>
                  <span className="text-slate-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-slate-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-slate-900">{module.display_name}</span>
                            {module.port && (
                              <span className="text-xs text-slate-400">:{module.port}</span>
                            )}
                          </div>
                          <div className="text-sm text-slate-500 mt-1">{module.name}</div>
                          {module.description && (
                            <div className="text-sm text-slate-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-slate-100 text-slate-600 text-xs rounded">
                                {tech}
                              </span>
                            ))}
                            {module.technology_stack.length > 4 && (
                              <span className="px-2 py-0.5 text-slate-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-slate-100'
                          } ${CRITICALITY_CONFIG[module.criticality]?.color || 'text-slate-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-slate-400 mt-1">
                            {module.regulation_count} Regulations
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}

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

          {/* Detail Panel */}
          {selectedModule && (
            <div className="w-96 bg-white rounded-xl shadow-sm border sticky top-6 h-fit">
              <div className={`px-4 py-3 border-b ${SERVICE_TYPE_CONFIG[selectedModule.service_type]?.bgColor || 'bg-slate-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-slate-400 hover:text-slate-600"
                  >
                    ✕
                  </button>
                </div>
                <h3 className="font-bold text-lg mt-2">{selectedModule.display_name}</h3>
                <div className="text-sm text-slate-600">{selectedModule.name}</div>
              </div>

              {loadingDetail ? (
                <div className="p-4 text-center text-slate-500">Lade Details...</div>
              ) : (
                <div className="p-4 space-y-4 max-h-[70vh] overflow-y-auto">
                  {selectedModule.description && (
                    <div>
                      <div className="text-xs text-slate-500 uppercase mb-1">Beschreibung</div>
                      <div className="text-sm text-slate-700">{selectedModule.description}</div>
                    </div>
                  )}

                  <div className="grid grid-cols-2 gap-2 text-sm">
                    {selectedModule.port && (
                      <div>
                        <span className="text-slate-500">Port:</span>
                        <span className="ml-1 font-mono">{selectedModule.port}</span>
                      </div>
                    )}
                    <div>
                      <span className="text-slate-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>

                  <div>
                    <div className="text-xs text-slate-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-slate-100 text-slate-700 text-xs rounded">
                          {tech}
                        </span>
                      ))}
                    </div>
                  </div>

                  {selectedModule.data_categories.length > 0 && (
                    <div>
                      <div className="text-xs text-slate-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>
                  )}

                  <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>

                  {selectedModule.regulations && selectedModule.regulations.length > 0 && (
                    <div>
                      <div className="text-xs text-slate-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-slate-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-slate-100'
                              } ${RELEVANCE_CONFIG[reg.relevance_level]?.color || 'text-slate-700'}`}>
                                {reg.relevance_level}
                              </span>
                            </div>
                            <div className="text-slate-500 text-xs">{reg.name}</div>
                            {reg.notes && (
                              <div className="text-slate-600 text-xs mt-1 italic">{reg.notes}</div>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

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

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

      {/* Regulations Coverage Overview */}
      {overview && overview.regulations_coverage && Object.keys(overview.regulations_coverage).length > 0 && (
        <div className="bg-white rounded-xl shadow-sm border p-4 mt-6">
          <h3 className="font-semibold text-slate-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-slate-50 rounded-lg p-3 text-center">
                  <div className="text-2xl font-bold text-blue-600">{count}</div>
                  <div className="text-xs text-slate-600 truncate" title={code}>{code}</div>
                </div>
              ))}
          </div>
        </div>
      )}
    </div>
  )
}
