'use client'

import React, { useState, useEffect } from 'react'
import { useSDK, Control as SDKControl, ControlType, ImplementationStatus, RiskSeverity } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'

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

type DisplayControlType = 'preventive' | 'detective' | 'corrective'
type DisplayCategory = 'technical' | 'organizational' | 'physical'
type DisplayStatus = 'implemented' | 'partial' | 'planned' | 'not-implemented'

// DisplayControl uses SDK Control properties but adds UI-specific fields
interface DisplayControl {
  // From SDKControl
  id: string
  name: string
  description: string
  type: ControlType
  category: string
  implementationStatus: ImplementationStatus
  evidence: string[]
  owner: string | null
  dueDate: Date | null
  // UI-specific fields
  code: string
  displayType: DisplayControlType
  displayCategory: DisplayCategory
  displayStatus: DisplayStatus
  effectivenessPercent: number
  linkedRequirements: string[]
  lastReview: Date
}

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

function mapControlTypeToDisplay(type: ControlType): DisplayCategory {
  switch (type) {
    case 'TECHNICAL': return 'technical'
    case 'ORGANIZATIONAL': return 'organizational'
    case 'PHYSICAL': return 'physical'
    default: return 'technical'
  }
}

function mapStatusToDisplay(status: ImplementationStatus): DisplayStatus {
  switch (status) {
    case 'IMPLEMENTED': return 'implemented'
    case 'PARTIAL': return 'partial'
    case 'NOT_IMPLEMENTED': return 'not-implemented'
    default: return 'not-implemented'
  }
}

// =============================================================================
// CONTROL TEMPLATES
// =============================================================================

interface ControlTemplate {
  id: string
  code: string
  name: string
  description: string
  type: ControlType
  displayType: DisplayControlType
  displayCategory: DisplayCategory
  category: string
  owner: string
  linkedRequirements: string[]
}

const controlTemplates: ControlTemplate[] = [
  {
    id: 'ctrl-tom-001',
    code: 'TOM-001',
    name: 'Zugriffskontrolle',
    description: 'Rollenbasierte Zugriffskontrolle (RBAC) fuer alle Systeme',
    type: 'TECHNICAL',
    displayType: 'preventive',
    displayCategory: 'technical',
    category: 'Zutrittskontrolle',
    owner: 'IT Security',
    linkedRequirements: ['req-gdpr-32'],
  },
  {
    id: 'ctrl-tom-002',
    code: 'TOM-002',
    name: 'Verschluesselung',
    description: 'Verschluesselung von Daten at rest und in transit',
    type: 'TECHNICAL',
    displayType: 'preventive',
    displayCategory: 'technical',
    category: 'Weitergabekontrolle',
    owner: 'IT Security',
    linkedRequirements: ['req-gdpr-32'],
  },
  {
    id: 'ctrl-org-001',
    code: 'ORG-001',
    name: 'Datenschutzschulung',
    description: 'Jaehrliche Datenschutzschulung fuer alle Mitarbeiter',
    type: 'ORGANIZATIONAL',
    displayType: 'preventive',
    displayCategory: 'organizational',
    category: 'Schulung',
    owner: 'HR',
    linkedRequirements: ['req-gdpr-6', 'req-gdpr-32'],
  },
  {
    id: 'ctrl-det-001',
    code: 'DET-001',
    name: 'Logging und Monitoring',
    description: 'Umfassendes Logging aller Datenzugriffe',
    type: 'TECHNICAL',
    displayType: 'detective',
    displayCategory: 'technical',
    category: 'Eingabekontrolle',
    owner: 'IT Operations',
    linkedRequirements: ['req-gdpr-32', 'req-nis2-21'],
  },
  {
    id: 'ctrl-cor-001',
    code: 'COR-001',
    name: 'Incident Response',
    description: 'Prozess zur Behandlung von Datenschutzvorfaellen',
    type: 'ORGANIZATIONAL',
    displayType: 'corrective',
    displayCategory: 'organizational',
    category: 'Incident Management',
    owner: 'CISO',
    linkedRequirements: ['req-gdpr-32', 'req-nis2-21'],
  },
  {
    id: 'ctrl-ai-001',
    code: 'AI-001',
    name: 'KI-Risikomonitoring',
    description: 'Kontinuierliche Ueberwachung von KI-Systemrisiken',
    type: 'TECHNICAL',
    displayType: 'detective',
    displayCategory: 'technical',
    category: 'KI-Governance',
    owner: 'AI Team',
    linkedRequirements: ['req-ai-act-9', 'req-ai-act-13'],
  },
]

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

function ControlCard({
  control,
  onStatusChange,
  onEffectivenessChange,
}: {
  control: DisplayControl
  onStatusChange: (status: ImplementationStatus) => void
  onEffectivenessChange: (effectivenessPercent: number) => void
}) {
  const [showEffectivenessSlider, setShowEffectivenessSlider] = useState(false)

  const typeColors = {
    preventive: 'bg-blue-100 text-blue-700',
    detective: 'bg-purple-100 text-purple-700',
    corrective: 'bg-orange-100 text-orange-700',
  }

  const categoryColors = {
    technical: 'bg-green-100 text-green-700',
    organizational: 'bg-yellow-100 text-yellow-700',
    physical: 'bg-gray-100 text-gray-700',
  }

  const statusColors = {
    implemented: 'border-green-200 bg-green-50',
    partial: 'border-yellow-200 bg-yellow-50',
    planned: 'border-blue-200 bg-blue-50',
    'not-implemented': 'border-red-200 bg-red-50',
  }

  const statusLabels = {
    implemented: 'Implementiert',
    partial: 'Teilweise',
    planned: 'Geplant',
    'not-implemented': 'Nicht implementiert',
  }

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${statusColors[control.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">
              {control.code}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${typeColors[control.displayType]}`}>
              {control.displayType === 'preventive' ? 'Praeventiv' :
               control.displayType === 'detective' ? 'Detektiv' : 'Korrektiv'}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${categoryColors[control.displayCategory]}`}>
              {control.displayCategory === 'technical' ? 'Technisch' :
               control.displayCategory === 'organizational' ? 'Organisatorisch' : 'Physisch'}
            </span>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">{control.name}</h3>
          <p className="text-sm text-gray-500 mt-1">{control.description}</p>
        </div>
        <select
          value={control.implementationStatus}
          onChange={(e) => onStatusChange(e.target.value as ImplementationStatus)}
          className={`px-3 py-1 text-sm rounded-full border ${statusColors[control.displayStatus]}`}
        >
          <option value="NOT_IMPLEMENTED">Nicht implementiert</option>
          <option value="PARTIAL">Teilweise</option>
          <option value="IMPLEMENTED">Implementiert</option>
        </select>
      </div>

      <div className="mt-4">
        <div
          className="flex items-center justify-between text-sm mb-1 cursor-pointer"
          onClick={() => setShowEffectivenessSlider(!showEffectivenessSlider)}
        >
          <span className="text-gray-500">Wirksamkeit</span>
          <span className="font-medium">{control.effectivenessPercent}%</span>
        </div>
        <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
          <div
            className={`h-full rounded-full transition-all ${
              control.effectivenessPercent >= 80 ? 'bg-green-500' :
              control.effectivenessPercent >= 50 ? 'bg-yellow-500' : 'bg-red-500'
            }`}
            style={{ width: `${control.effectivenessPercent}%` }}
          />
        </div>
        {showEffectivenessSlider && (
          <div className="mt-2">
            <input
              type="range"
              min={0}
              max={100}
              value={control.effectivenessPercent}
              onChange={(e) => onEffectivenessChange(Number(e.target.value))}
              className="w-full"
            />
          </div>
        )}
      </div>

      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between text-sm">
        <div className="text-gray-500">
          <span>Verantwortlich: </span>
          <span className="font-medium text-gray-700">{control.owner || 'Nicht zugewiesen'}</span>
        </div>
        <div className="text-gray-500">
          Letzte Pruefung: {control.lastReview.toLocaleDateString('de-DE')}
        </div>
      </div>

      <div className="mt-3 flex items-center justify-between">
        <div className="flex items-center gap-1 flex-wrap">
          {control.linkedRequirements.slice(0, 3).map(req => (
            <span key={req} className="px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded">
              {req}
            </span>
          ))}
          {control.linkedRequirements.length > 3 && (
            <span className="px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded">
              +{control.linkedRequirements.length - 3}
            </span>
          )}
        </div>
        <span className={`px-3 py-1 text-xs rounded-full ${
          control.displayStatus === 'implemented' ? 'bg-green-100 text-green-700' :
          control.displayStatus === 'partial' ? 'bg-yellow-100 text-yellow-700' :
          control.displayStatus === 'planned' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'
        }`}>
          {statusLabels[control.displayStatus]}
        </span>
      </div>
    </div>
  )
}

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

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

  // Track effectiveness locally as it's not in the SDK state type
  const [effectivenessMap, setEffectivenessMap] = useState<Record<string, number>>({})

  // Load controls based on requirements when requirements exist
  useEffect(() => {
    if (state.requirements.length > 0 && state.controls.length === 0) {
      // Add relevant controls based on requirements
      const relevantControls = controlTemplates.filter(c =>
        c.linkedRequirements.some(reqId => state.requirements.some(r => r.id === reqId))
      )

      relevantControls.forEach(ctrl => {
        const sdkControl: SDKControl = {
          id: ctrl.id,
          name: ctrl.name,
          description: ctrl.description,
          type: ctrl.type,
          category: ctrl.category,
          implementationStatus: 'NOT_IMPLEMENTED',
          effectiveness: 'LOW',
          evidence: [],
          owner: ctrl.owner,
          dueDate: null,
        }
        dispatch({ type: 'ADD_CONTROL', payload: sdkControl })
      })
    }
  }, [state.requirements, state.controls.length, dispatch])

  // Convert SDK controls to display controls
  const displayControls: DisplayControl[] = state.controls.map(ctrl => {
    const template = controlTemplates.find(t => t.id === ctrl.id)
    const effectivenessPercent = effectivenessMap[ctrl.id] ??
      (ctrl.implementationStatus === 'IMPLEMENTED' ? 85 :
       ctrl.implementationStatus === 'PARTIAL' ? 50 : 0)

    return {
      id: ctrl.id,
      name: ctrl.name,
      description: ctrl.description,
      type: ctrl.type,
      category: ctrl.category,
      implementationStatus: ctrl.implementationStatus,
      evidence: ctrl.evidence,
      owner: ctrl.owner,
      dueDate: ctrl.dueDate,
      code: template?.code || ctrl.id,
      displayType: template?.displayType || 'preventive',
      displayCategory: mapControlTypeToDisplay(ctrl.type),
      displayStatus: mapStatusToDisplay(ctrl.implementationStatus),
      effectivenessPercent,
      linkedRequirements: template?.linkedRequirements || [],
      lastReview: new Date(),
    }
  })

  const filteredControls = filter === 'all'
    ? displayControls
    : displayControls.filter(c =>
        c.displayStatus === filter ||
        c.displayType === filter ||
        c.displayCategory === filter
      )

  const implementedCount = displayControls.filter(c => c.displayStatus === 'implemented').length
  const avgEffectiveness = displayControls.length > 0
    ? Math.round(displayControls.reduce((sum, c) => sum + c.effectivenessPercent, 0) / displayControls.length)
    : 0
  const partialCount = displayControls.filter(c => c.displayStatus === 'partial').length

  const handleStatusChange = (controlId: string, status: ImplementationStatus) => {
    dispatch({
      type: 'UPDATE_CONTROL',
      payload: { id: controlId, data: { implementationStatus: status } },
    })
  }

  const handleEffectivenessChange = (controlId: string, effectiveness: number) => {
    setEffectivenessMap(prev => ({ ...prev, [controlId]: effectiveness }))
  }

  const stepInfo = STEP_EXPLANATIONS['controls']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="controls"
        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>
          Kontrolle hinzufuegen
        </button>
      </StepHeader>

      {/* Requirements Alert */}
      {state.requirements.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 Anforderungen definiert</h4>
              <p className="text-sm text-amber-700 mt-1">
                Bitte definieren Sie zuerst Anforderungen, um die zugehoerigen Kontrollen 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">{displayControls.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Implementiert</div>
          <div className="text-3xl font-bold text-green-600">{implementedCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-purple-200 p-6">
          <div className="text-sm text-purple-600">Durchschn. Wirksamkeit</div>
          <div className="text-3xl font-bold text-purple-600">{avgEffectiveness}%</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-6">
          <div className="text-sm text-yellow-600">Teilweise</div>
          <div className="text-3xl font-bold text-yellow-600">{partialCount}</div>
        </div>
      </div>

      {/* Filter */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'implemented', 'partial', 'not-implemented', 'technical', 'organizational', 'preventive', 'detective'].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 === 'implemented' ? 'Implementiert' :
             f === 'partial' ? 'Teilweise' :
             f === 'not-implemented' ? 'Offen' :
             f === 'technical' ? 'Technisch' :
             f === 'organizational' ? 'Organisatorisch' :
             f === 'preventive' ? 'Praeventiv' : 'Detektiv'}
          </button>
        ))}
      </div>

      {/* Controls List */}
      <div className="space-y-4">
        {filteredControls.map(control => (
          <ControlCard
            key={control.id}
            control={control}
            onStatusChange={(status) => handleStatusChange(control.id, status)}
            onEffectivenessChange={(effectiveness) => handleEffectivenessChange(control.id, effectiveness)}
          />
        ))}
      </div>

      {filteredControls.length === 0 && state.requirements.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 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Kontrollen gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an oder fuegen Sie neue Kontrollen hinzu.</p>
        </div>
      )}
    </div>
  )
}
