'use client'

// =============================================================================
// Step 4: Security Profile
// Authentication, encryption, and security configuration
// =============================================================================

import React, { useState, useEffect } from 'react'
import { useTOMGenerator } from '@/lib/sdk/tom-generator'
import {
  SecurityProfile,
  AuthMethodType,
  BackupFrequency,
} from '@/lib/sdk/tom-generator/types'

// =============================================================================
// CONSTANTS
// =============================================================================

const AUTH_METHODS: { value: AuthMethodType; label: string; description: string }[] = [
  { value: 'PASSWORD', label: 'Passwort', description: 'Standard-Passwortauthentifizierung' },
  { value: 'MFA', label: 'Multi-Faktor (MFA)', description: 'Zweiter Faktor erforderlich' },
  { value: 'SSO', label: 'Single Sign-On', description: 'Zentralisierte Anmeldung' },
  { value: 'CERTIFICATE', label: 'Zertifikat', description: 'Client-Zertifikate' },
  { value: 'BIOMETRIC', label: 'Biometrisch', description: 'Fingerabdruck, Gesicht, etc.' },
]

const BACKUP_FREQUENCIES: { value: BackupFrequency; label: string }[] = [
  { value: 'HOURLY', label: 'Stündlich' },
  { value: 'DAILY', label: 'Täglich' },
  { value: 'WEEKLY', label: 'Wöchentlich' },
  { value: 'MONTHLY', label: 'Monatlich' },
]

// =============================================================================
// COMPONENT
// =============================================================================

export function SecurityProfileStep() {
  const { state, setSecurityProfile, completeCurrentStep } = useTOMGenerator()

  const [formData, setFormData] = useState<Partial<SecurityProfile>>({
    authMethods: [],
    hasMFA: false,
    hasSSO: false,
    hasIAM: false,
    hasPAM: false,
    hasEncryptionAtRest: false,
    hasEncryptionInTransit: false,
    hasLogging: false,
    logRetentionDays: 90,
    hasBackup: false,
    backupFrequency: 'DAILY',
    backupRetentionDays: 30,
    hasDRPlan: false,
    rtoHours: null,
    rpoHours: null,
    hasVulnerabilityManagement: false,
    hasPenetrationTests: false,
    hasSecurityTraining: false,
  })

  // Load existing data
  useEffect(() => {
    if (state.securityProfile) {
      setFormData(state.securityProfile)
    }
  }, [state.securityProfile])

  // Sync auth methods with boolean flags
  useEffect(() => {
    const authTypes = formData.authMethods?.map((m) => m.type) || []
    setFormData((prev) => ({
      ...prev,
      hasMFA: authTypes.includes('MFA'),
      hasSSO: authTypes.includes('SSO'),
    }))
  }, [formData.authMethods])

  // Handle auth method toggle
  const toggleAuthMethod = (method: AuthMethodType) => {
    setFormData((prev) => {
      const current = prev.authMethods || []
      const exists = current.some((m) => m.type === method)
      const updated = exists
        ? current.filter((m) => m.type !== method)
        : [...current, { type: method, provider: null }]
      return { ...prev, authMethods: updated }
    })
  }

  // Handle submit
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()

    const profile: SecurityProfile = {
      authMethods: formData.authMethods || [],
      hasMFA: formData.hasMFA || false,
      hasSSO: formData.hasSSO || false,
      hasIAM: formData.hasIAM || false,
      hasPAM: formData.hasPAM || false,
      hasEncryptionAtRest: formData.hasEncryptionAtRest || false,
      hasEncryptionInTransit: formData.hasEncryptionInTransit || false,
      hasLogging: formData.hasLogging || false,
      logRetentionDays: formData.logRetentionDays || 90,
      hasBackup: formData.hasBackup || false,
      backupFrequency: formData.backupFrequency || 'DAILY',
      backupRetentionDays: formData.backupRetentionDays || 30,
      hasDRPlan: formData.hasDRPlan || false,
      rtoHours: formData.rtoHours ?? null,
      rpoHours: formData.rpoHours ?? null,
      hasVulnerabilityManagement: formData.hasVulnerabilityManagement || false,
      hasPenetrationTests: formData.hasPenetrationTests || false,
      hasSecurityTraining: formData.hasSecurityTraining || false,
    }

    setSecurityProfile(profile)
    completeCurrentStep(profile)
  }

  const selectedAuthMethods = formData.authMethods?.map((m) => m.type) || []

  return (
    <form onSubmit={handleSubmit} className="space-y-8">
      {/* Authentication Methods */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Authentifizierungsmethoden</h3>
        <p className="text-sm text-gray-600 mb-4">
          Welche Authentifizierungsmethoden werden verwendet?
        </p>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
          {AUTH_METHODS.map((method) => (
            <label
              key={method.value}
              className={`relative flex items-start p-3 border rounded-lg cursor-pointer transition-all ${
                selectedAuthMethods.includes(method.value)
                  ? 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
            >
              <input
                type="checkbox"
                checked={selectedAuthMethods.includes(method.value)}
                onChange={() => toggleAuthMethod(method.value)}
                className="sr-only"
              />
              <div className="flex-1">
                <span className="font-medium text-gray-900">{method.label}</span>
                <p className="text-xs text-gray-500 mt-0.5">{method.description}</p>
              </div>
              {selectedAuthMethods.includes(method.value) && (
                <svg className="w-5 h-5 text-blue-500" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                </svg>
              )}
            </label>
          ))}
        </div>

        {/* MFA recommendation */}
        {!selectedAuthMethods.includes('MFA') && (
          <div className="mt-4 bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <p className="text-sm text-yellow-800">
              <strong>Empfehlung:</strong> Multi-Faktor-Authentifizierung (MFA) wird für alle sensiblen
              Systeme dringend empfohlen und ist bei besonderen Datenkategorien oft erforderlich.
            </p>
          </div>
        )}
      </div>

      {/* Identity & Access Management */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Identity & Access Management</h3>

        <div className="space-y-3">
          <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50">
            <input
              type="checkbox"
              checked={formData.hasIAM || false}
              onChange={(e) => setFormData((prev) => ({ ...prev, hasIAM: e.target.checked }))}
              className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <div>
              <span className="text-gray-700 font-medium">Identity & Access Management (IAM)</span>
              <p className="text-sm text-gray-500">Zentralisierte Benutzer- und Berechtigungsverwaltung</p>
            </div>
          </label>

          <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50">
            <input
              type="checkbox"
              checked={formData.hasPAM || false}
              onChange={(e) => setFormData((prev) => ({ ...prev, hasPAM: e.target.checked }))}
              className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <div>
              <span className="text-gray-700 font-medium">Privileged Access Management (PAM)</span>
              <p className="text-sm text-gray-500">Kontrolle privilegierter Zugänge (Admin-Konten)</p>
            </div>
          </label>
        </div>
      </div>

      {/* Encryption */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Verschlüsselung</h3>

        <div className="space-y-3">
          <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50">
            <input
              type="checkbox"
              checked={formData.hasEncryptionAtRest || false}
              onChange={(e) => setFormData((prev) => ({ ...prev, hasEncryptionAtRest: e.target.checked }))}
              className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <div>
              <span className="text-gray-700 font-medium">Verschlüsselung ruhender Daten</span>
              <p className="text-sm text-gray-500">AES-256 oder vergleichbar für gespeicherte Daten</p>
            </div>
          </label>

          <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50">
            <input
              type="checkbox"
              checked={formData.hasEncryptionInTransit || false}
              onChange={(e) => setFormData((prev) => ({ ...prev, hasEncryptionInTransit: e.target.checked }))}
              className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <div>
              <span className="text-gray-700 font-medium">Transportverschlüsselung</span>
              <p className="text-sm text-gray-500">TLS 1.2+ für alle Datenübertragungen</p>
            </div>
          </label>
        </div>
      </div>

      {/* Logging */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Protokollierung</h3>

        <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50 mb-4">
          <input
            type="checkbox"
            checked={formData.hasLogging || false}
            onChange={(e) => setFormData((prev) => ({ ...prev, hasLogging: e.target.checked }))}
            className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
          />
          <div>
            <span className="text-gray-700 font-medium">Audit-Logging aktiviert</span>
            <p className="text-sm text-gray-500">Protokollierung aller sicherheitsrelevanten Ereignisse</p>
          </div>
        </label>

        {formData.hasLogging && (
          <div className="pl-8">
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Log-Aufbewahrung (Tage)
            </label>
            <input
              type="number"
              min="1"
              value={formData.logRetentionDays || 90}
              onChange={(e) => setFormData((prev) => ({ ...prev, logRetentionDays: parseInt(e.target.value) || 90 }))}
              className="w-32 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            />
          </div>
        )}
      </div>

      {/* Backup & DR */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Backup & Disaster Recovery</h3>

        <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50 mb-4">
          <input
            type="checkbox"
            checked={formData.hasBackup || false}
            onChange={(e) => setFormData((prev) => ({ ...prev, hasBackup: e.target.checked }))}
            className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
          />
          <div>
            <span className="text-gray-700 font-medium">Regelmäßige Backups</span>
            <p className="text-sm text-gray-500">Automatisierte Datensicherung</p>
          </div>
        </label>

        {formData.hasBackup && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pl-8 mb-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Backup-Frequenz
              </label>
              <select
                value={formData.backupFrequency || 'DAILY'}
                onChange={(e) => setFormData((prev) => ({ ...prev, backupFrequency: e.target.value as BackupFrequency }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                {BACKUP_FREQUENCIES.map((freq) => (
                  <option key={freq.value} value={freq.value}>{freq.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Backup-Aufbewahrung (Tage)
              </label>
              <input
                type="number"
                min="1"
                value={formData.backupRetentionDays || 30}
                onChange={(e) => setFormData((prev) => ({ ...prev, backupRetentionDays: parseInt(e.target.value) || 30 }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>
        )}

        <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50 mb-4">
          <input
            type="checkbox"
            checked={formData.hasDRPlan || false}
            onChange={(e) => setFormData((prev) => ({ ...prev, hasDRPlan: e.target.checked }))}
            className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
          />
          <div>
            <span className="text-gray-700 font-medium">Disaster Recovery Plan vorhanden</span>
            <p className="text-sm text-gray-500">Dokumentierter Wiederherstellungsplan</p>
          </div>
        </label>

        {formData.hasDRPlan && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pl-8">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                RTO (Recovery Time Objective) in Stunden
              </label>
              <input
                type="number"
                min="0"
                step="0.5"
                value={formData.rtoHours ?? ''}
                onChange={(e) => setFormData((prev) => ({ ...prev, rtoHours: e.target.value ? parseFloat(e.target.value) : null }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                placeholder="z.B. 4"
              />
              <p className="text-xs text-gray-500 mt-1">Maximale Ausfallzeit</p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                RPO (Recovery Point Objective) in Stunden
              </label>
              <input
                type="number"
                min="0"
                step="0.25"
                value={formData.rpoHours ?? ''}
                onChange={(e) => setFormData((prev) => ({ ...prev, rpoHours: e.target.value ? parseFloat(e.target.value) : null }))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                placeholder="z.B. 1"
              />
              <p className="text-xs text-gray-500 mt-1">Maximaler Datenverlust</p>
            </div>
          </div>
        )}
      </div>

      {/* Security Testing & Training */}
      <div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Sicherheitstests & Schulungen</h3>

        <div className="space-y-3">
          <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50">
            <input
              type="checkbox"
              checked={formData.hasVulnerabilityManagement || false}
              onChange={(e) => setFormData((prev) => ({ ...prev, hasVulnerabilityManagement: e.target.checked }))}
              className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <div>
              <span className="text-gray-700 font-medium">Schwachstellenmanagement</span>
              <p className="text-sm text-gray-500">Regelmäßige Schwachstellenscans und Patch-Management</p>
            </div>
          </label>

          <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50">
            <input
              type="checkbox"
              checked={formData.hasPenetrationTests || false}
              onChange={(e) => setFormData((prev) => ({ ...prev, hasPenetrationTests: e.target.checked }))}
              className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <div>
              <span className="text-gray-700 font-medium">Penetrationstests</span>
              <p className="text-sm text-gray-500">Regelmäßige Sicherheitstests durch externe Prüfer</p>
            </div>
          </label>

          <label className="flex items-center gap-3 cursor-pointer p-3 border rounded-lg hover:bg-gray-50">
            <input
              type="checkbox"
              checked={formData.hasSecurityTraining || false}
              onChange={(e) => setFormData((prev) => ({ ...prev, hasSecurityTraining: e.target.checked }))}
              className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <div>
              <span className="text-gray-700 font-medium">Security Awareness Training</span>
              <p className="text-sm text-gray-500">Regelmäßige Schulungen für alle Mitarbeiter</p>
            </div>
          </label>
        </div>
      </div>
    </form>
  )
}

export default SecurityProfileStep
