'use client'

import React, { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'

interface ModuleDetail {
  id: string
  name: string
  display_name: string
  description: string
  is_active: boolean
  criticality: string
  processes_pii: boolean
  ai_components: boolean
  compliance_score: number | null
  regulation_count: number
  risk_count: number
  requirements?: Array<{
    id: string
    title: string
    status: string
    regulation: string
  }>
  controls?: Array<{
    id: string
    title: string
    status: string
    description: string
  }>
  regulations?: string[]
}

export default function ModuleDetailPage() {
  const params = useParams()
  const router = useRouter()
  const moduleId = params.moduleId as string

  const [module, setModule] = useState<ModuleDetail | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    async function load() {
      try {
        const response = await fetch(`/api/sdk/v1/modules/${encodeURIComponent(moduleId)}`)
        if (!response.ok) {
          throw new Error('Modul nicht gefunden')
        }
        const data = await response.json()
        setModule(data)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Fehler beim Laden')
      } finally {
        setLoading(false)
      }
    }
    if (moduleId) load()
  }, [moduleId])

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-gray-500">Lade Modul-Details...</div>
      </div>
    )
  }

  if (error || !module) {
    return (
      <div className="space-y-4">
        <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
          <h3 className="text-lg font-semibold text-red-800">Fehler</h3>
          <p className="text-red-600 mt-1">{error || 'Modul nicht gefunden'}</p>
        </div>
        <Link href="/sdk/modules" className="text-purple-600 hover:text-purple-700">
          Zurueck zur Uebersicht
        </Link>
      </div>
    )
  }

  const criticalityColors: Record<string, string> = {
    HIGH: 'bg-red-100 text-red-700',
    MEDIUM: 'bg-yellow-100 text-yellow-700',
    LOW: 'bg-green-100 text-green-700',
  }

  return (
    <div className="space-y-6">
      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm text-gray-500">
        <Link href="/sdk/modules" className="hover:text-purple-600">Module</Link>
        <span>/</span>
        <span className="text-gray-900">{module.display_name || module.name}</span>
      </div>

      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">{module.display_name || module.name}</h1>
          <p className="text-gray-500 mt-1">{module.description}</p>
          <div className="flex items-center gap-3 mt-3">
            <span className={`px-2 py-1 text-xs rounded-full ${module.is_active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
              {module.is_active ? 'Aktiv' : 'Inaktiv'}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${criticalityColors[module.criticality?.toUpperCase()] || 'bg-gray-100 text-gray-700'}`}>
              {module.criticality}
            </span>
            {module.processes_pii && (
              <span className="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-700">PII</span>
            )}
            {module.ai_components && (
              <span className="px-2 py-1 text-xs rounded-full bg-indigo-100 text-indigo-700">KI</span>
            )}
          </div>
        </div>
        <button
          onClick={() => router.push('/sdk/modules')}
          className="px-4 py-2 text-sm bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
        >
          Zurueck
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="text-sm text-gray-500">Compliance Score</div>
          <div className="text-3xl font-bold text-purple-600">
            {module.compliance_score != null ? `${module.compliance_score}%` : '—'}
          </div>
        </div>
        <div className="bg-white rounded-xl border border-blue-200 p-6">
          <div className="text-sm text-blue-600">Regulierungen</div>
          <div className="text-3xl font-bold text-blue-600">{module.regulation_count || 0}</div>
        </div>
        <div className="bg-white rounded-xl border border-orange-200 p-6">
          <div className="text-sm text-orange-600">Risiken</div>
          <div className="text-3xl font-bold text-orange-600">{module.risk_count || 0}</div>
        </div>
      </div>

      {/* Requirements */}
      {module.requirements && module.requirements.length > 0 && (
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-gray-200 bg-gray-50">
            <h3 className="font-semibold text-gray-900">Anforderungen</h3>
          </div>
          <div className="divide-y divide-gray-100">
            {module.requirements.map(req => (
              <div key={req.id} className="px-6 py-4 flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-900">{req.title}</p>
                  <p className="text-xs text-gray-500">{req.regulation}</p>
                </div>
                <span className={`px-2 py-1 text-xs rounded-full ${
                  req.status === 'IMPLEMENTED' || req.status === 'VERIFIED'
                    ? 'bg-green-100 text-green-700'
                    : req.status === 'IN_PROGRESS'
                    ? 'bg-yellow-100 text-yellow-700'
                    : 'bg-gray-100 text-gray-500'
                }`}>
                  {req.status}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Controls */}
      {module.controls && module.controls.length > 0 && (
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-gray-200 bg-gray-50">
            <h3 className="font-semibold text-gray-900">Kontrollen</h3>
          </div>
          <div className="divide-y divide-gray-100">
            {module.controls.map(ctrl => (
              <div key={ctrl.id} className="px-6 py-4">
                <div className="flex items-center justify-between">
                  <p className="text-sm font-medium text-gray-900">{ctrl.title}</p>
                  <span className={`px-2 py-1 text-xs rounded-full ${
                    ctrl.status === 'IMPLEMENTED' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                  }`}>
                    {ctrl.status}
                  </span>
                </div>
                <p className="text-xs text-gray-500 mt-1">{ctrl.description}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Regulations */}
      {module.regulations && module.regulations.length > 0 && (
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h3 className="font-semibold text-gray-900 mb-3">Zugeordnete Regulierungen</h3>
          <div className="flex flex-wrap gap-2">
            {module.regulations.map(reg => (
              <span key={reg} className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded-full">{reg}</span>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
