'use client'

import React, { useState, useEffect } from 'react'
import { useSDK, Requirement as SDKRequirement, RequirementStatus, RiskSeverity } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'

// =============================================================================
// TYPES
// =============================================================================

type DisplayPriority = 'critical' | 'high' | 'medium' | 'low'
type DisplayStatus = 'compliant' | 'partial' | 'non-compliant' | 'not-applicable'

interface DisplayRequirement extends SDKRequirement {
  code: string
  source: string
  category: string
  priority: DisplayPriority
  displayStatus: DisplayStatus
  controlsLinked: number
  evidenceCount: number
}

// =============================================================================
// HELPER FUNCTIONS
// =============================================================================

function mapCriticalityToPriority(criticality: RiskSeverity): DisplayPriority {
  switch (criticality) {
    case 'CRITICAL': return 'critical'
    case 'HIGH': return 'high'
    case 'MEDIUM': return 'medium'
    case 'LOW': return 'low'
    default: return 'medium'
  }
}

function mapStatusToDisplayStatus(status: RequirementStatus): DisplayStatus {
  switch (status) {
    case 'VERIFIED':
    case 'IMPLEMENTED': return 'compliant'
    case 'IN_PROGRESS': return 'partial'
    case 'NOT_STARTED': return 'non-compliant'
    default: return 'non-compliant'
  }
}

// =============================================================================
// AVAILABLE REQUIREMENTS (Templates)
// =============================================================================

const requirementTemplates: Omit<DisplayRequirement, 'displayStatus' | 'controlsLinked' | 'evidenceCount'>[] = [
  {
    id: 'req-gdpr-6',
    regulation: 'DSGVO',
    article: 'Art. 6',
    code: 'GDPR-6.1',
    title: 'Rechtmaessigkeit der Verarbeitung',
    description: 'Personenbezogene Daten duerfen nur verarbeitet werden, wenn eine Rechtsgrundlage vorliegt.',
    source: 'DSGVO Art. 6',
    category: 'Rechtmaessigkeit',
    priority: 'critical',
    criticality: 'CRITICAL',
    applicableModules: ['mod-gdpr'],
    status: 'NOT_STARTED',
    controls: [],
  },
  {
    id: 'req-gdpr-13',
    regulation: 'DSGVO',
    article: 'Art. 13/14',
    code: 'GDPR-13',
    title: 'Informationspflichten',
    description: 'Betroffene Personen muessen ueber die Datenverarbeitung informiert werden.',
    source: 'DSGVO Art. 13/14',
    category: 'Transparenz',
    priority: 'high',
    criticality: 'HIGH',
    applicableModules: ['mod-gdpr'],
    status: 'NOT_STARTED',
    controls: [],
  },
  {
    id: 'req-ai-act-9',
    regulation: 'AI Act',
    article: 'Art. 9',
    code: 'AI-ACT-9',
    title: 'Risikomanagementsystem',
    description: 'Hochrisiko-KI-Systeme erfordern ein Risikomanagementsystem.',
    source: 'AI Act Art. 9',
    category: 'KI-Governance',
    priority: 'high',
    criticality: 'HIGH',
    applicableModules: ['mod-ai-act'],
    status: 'NOT_STARTED',
    controls: [],
  },
  {
    id: 'req-gdpr-32',
    regulation: 'DSGVO',
    article: 'Art. 32',
    code: 'GDPR-32',
    title: 'Sicherheit der Verarbeitung',
    description: 'Geeignete technische und organisatorische Massnahmen zur Datensicherheit.',
    source: 'DSGVO Art. 32',
    category: 'Sicherheit',
    priority: 'critical',
    criticality: 'CRITICAL',
    applicableModules: ['mod-gdpr', 'mod-iso27001'],
    status: 'NOT_STARTED',
    controls: [],
  },
  {
    id: 'req-gdpr-35',
    regulation: 'DSGVO',
    article: 'Art. 35',
    code: 'GDPR-35',
    title: 'Datenschutz-Folgenabschaetzung',
    description: 'Bei hohem Risiko ist eine DSFA durchzufuehren.',
    source: 'DSGVO Art. 35',
    category: 'Risikobewertung',
    priority: 'high',
    criticality: 'HIGH',
    applicableModules: ['mod-gdpr'],
    status: 'NOT_STARTED',
    controls: [],
  },
  {
    id: 'req-ai-act-13',
    regulation: 'AI Act',
    article: 'Art. 13',
    code: 'AI-ACT-13',
    title: 'Transparenzanforderungen',
    description: 'KI-Systeme muessen fuer Nutzer nachvollziehbar und transparent sein.',
    source: 'AI Act Art. 13',
    category: 'Transparenz',
    priority: 'high',
    criticality: 'HIGH',
    applicableModules: ['mod-ai-act'],
    status: 'NOT_STARTED',
    controls: [],
  },
  {
    id: 'req-nis2-21',
    regulation: 'NIS2',
    article: 'Art. 21',
    code: 'NIS2-21',
    title: 'Risikomanagementmassnahmen',
    description: 'Wesentliche und wichtige Einrichtungen muessen Cybersicherheitsmassnahmen implementieren.',
    source: 'NIS2 Art. 21',
    category: 'Cybersicherheit',
    priority: 'high',
    criticality: 'HIGH',
    applicableModules: ['mod-nis2'],
    status: 'NOT_STARTED',
    controls: [],
  },
]

// =============================================================================
// COMPONENTS
// =============================================================================

function RequirementCard({
  requirement,
  onStatusChange,
}: {
  requirement: DisplayRequirement
  onStatusChange: (status: RequirementStatus) => void
}) {
  const priorityColors = {
    critical: 'bg-red-100 text-red-700',
    high: 'bg-orange-100 text-orange-700',
    medium: 'bg-yellow-100 text-yellow-700',
    low: 'bg-green-100 text-green-700',
  }

  const statusColors = {
    compliant: 'bg-green-100 text-green-700 border-green-200',
    partial: 'bg-yellow-100 text-yellow-700 border-yellow-200',
    'non-compliant': 'bg-red-100 text-red-700 border-red-200',
    'not-applicable': 'bg-gray-100 text-gray-500 border-gray-200',
  }

  const statusLabels = {
    compliant: 'Konform',
    partial: 'Teilweise',
    'non-compliant': 'Nicht konform',
    'not-applicable': 'N/A',
  }

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${statusColors[requirement.displayStatus]}`}>
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-2">
            <span className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded font-mono">
              {requirement.code}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${priorityColors[requirement.priority]}`}>
              {requirement.priority === 'critical' ? 'Kritisch' :
               requirement.priority === 'high' ? 'Hoch' :
               requirement.priority === 'medium' ? 'Mittel' : 'Niedrig'}
            </span>
            <span className="px-2 py-1 text-xs bg-blue-50 text-blue-600 rounded">
              {requirement.regulation}
            </span>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">{requirement.title}</h3>
          <p className="text-sm text-gray-500 mt-1">{requirement.description}</p>
          <p className="text-xs text-gray-400 mt-2">Quelle: {requirement.source}</p>
        </div>
        <select
          value={requirement.status}
          onChange={(e) => onStatusChange(e.target.value as RequirementStatus)}
          className={`px-3 py-1 text-sm rounded-full border ${statusColors[requirement.displayStatus]}`}
        >
          <option value="NOT_STARTED">Nicht begonnen</option>
          <option value="IN_PROGRESS">In Bearbeitung</option>
          <option value="IMPLEMENTED">Implementiert</option>
          <option value="VERIFIED">Verifiziert</option>
        </select>
      </div>

      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between">
        <div className="flex items-center gap-4 text-sm text-gray-500">
          <span>{requirement.controlsLinked} Kontrollen</span>
          <span>{requirement.evidenceCount} Nachweise</span>
        </div>
        <button className="text-sm text-purple-600 hover:text-purple-700 font-medium">
          Details anzeigen
        </button>
      </div>
    </div>
  )
}

// =============================================================================
// MAIN PAGE
// =============================================================================

export default function RequirementsPage() {
  const { state, dispatch } = useSDK()
  const [filter, setFilter] = useState<string>('all')
  const [searchQuery, setSearchQuery] = useState('')

  // Load requirements based on active modules
  useEffect(() => {
    // Only add requirements if there are active modules and no requirements yet
    if (state.modules.length > 0 && state.requirements.length === 0) {
      const activeModuleIds = state.modules.map(m => m.id)
      const relevantRequirements = requirementTemplates.filter(r =>
        r.applicableModules.some(m => activeModuleIds.includes(m))
      )

      relevantRequirements.forEach(req => {
        const sdkRequirement: SDKRequirement = {
          id: req.id,
          regulation: req.regulation,
          article: req.article,
          title: req.title,
          description: req.description,
          criticality: req.criticality,
          applicableModules: req.applicableModules,
          status: 'NOT_STARTED',
          controls: [],
        }
        dispatch({ type: 'ADD_REQUIREMENT', payload: sdkRequirement })
      })
    }
  }, [state.modules, state.requirements.length, dispatch])

  // Convert SDK requirements to display requirements
  const displayRequirements: DisplayRequirement[] = state.requirements.map(req => {
    const template = requirementTemplates.find(t => t.id === req.id)
    const linkedControls = state.controls.filter(c => c.evidence.includes(req.id))
    const linkedEvidence = state.evidence.filter(e => e.controlId && linkedControls.some(c => c.id === e.controlId))

    return {
      ...req,
      code: template?.code || req.id,
      source: template?.source || `${req.regulation} ${req.article}`,
      category: template?.category || req.regulation,
      priority: mapCriticalityToPriority(req.criticality),
      displayStatus: mapStatusToDisplayStatus(req.status),
      controlsLinked: linkedControls.length,
      evidenceCount: linkedEvidence.length,
    }
  })

  const filteredRequirements = displayRequirements.filter(req => {
    const matchesFilter = filter === 'all' ||
      req.displayStatus === filter ||
      req.priority === filter
    const matchesSearch = searchQuery === '' ||
      req.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      req.code.toLowerCase().includes(searchQuery.toLowerCase())
    return matchesFilter && matchesSearch
  })

  const compliantCount = displayRequirements.filter(r => r.displayStatus === 'compliant').length
  const partialCount = displayRequirements.filter(r => r.displayStatus === 'partial').length
  const nonCompliantCount = displayRequirements.filter(r => r.displayStatus === 'non-compliant').length

  const handleStatusChange = (requirementId: string, status: RequirementStatus) => {
    dispatch({
      type: 'UPDATE_REQUIREMENT',
      payload: { id: requirementId, data: { status } },
    })
  }

  const stepInfo = STEP_EXPLANATIONS['requirements']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="requirements"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <button className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
          Anforderung hinzufuegen
        </button>
      </StepHeader>

      {/* Module Alert */}
      {state.modules.length === 0 && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
          <div className="flex items-start gap-3">
            <svg className="w-5 h-5 text-amber-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <div>
              <h4 className="font-medium text-amber-800">Keine Module aktiviert</h4>
              <p className="text-sm text-amber-700 mt-1">
                Bitte aktivieren Sie zuerst Compliance-Module, um die zugehoerigen Anforderungen zu laden.
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="text-sm text-gray-500">Gesamt</div>
          <div className="text-3xl font-bold text-gray-900">{displayRequirements.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Konform</div>
          <div className="text-3xl font-bold text-green-600">{compliantCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-6">
          <div className="text-sm text-yellow-600">In Bearbeitung</div>
          <div className="text-3xl font-bold text-yellow-600">{partialCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-red-200 p-6">
          <div className="text-sm text-red-600">Offen</div>
          <div className="text-3xl font-bold text-red-600">{nonCompliantCount}</div>
        </div>
      </div>

      {/* Search and Filter */}
      <div className="flex items-center gap-4">
        <div className="flex-1 relative">
          <svg className="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Anforderungen durchsuchen..."
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
          />
        </div>
        <div className="flex items-center gap-2">
          {['all', 'compliant', 'partial', 'non-compliant', 'critical'].map(f => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1 text-sm rounded-full transition-colors ${
                filter === f
                  ? 'bg-purple-600 text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              {f === 'all' ? 'Alle' :
               f === 'compliant' ? 'Konform' :
               f === 'partial' ? 'Teilweise' :
               f === 'non-compliant' ? 'Offen' : 'Kritisch'}
            </button>
          ))}
        </div>
      </div>

      {/* Requirements List */}
      <div className="space-y-4">
        {filteredRequirements.map(requirement => (
          <RequirementCard
            key={requirement.id}
            requirement={requirement}
            onStatusChange={(status) => handleStatusChange(requirement.id, status)}
          />
        ))}
      </div>

      {filteredRequirements.length === 0 && state.modules.length > 0 && (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Anforderungen gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie die Suche oder den Filter an.</p>
        </div>
      )}
    </div>
  )
}
