'use client'

/**
 * Audit Export Wizard
 *
 * Features:
 * - Export type selection
 * - Scope filtering (regulations, domains)
 * - Export generation
 * - Download
 * - Export history
 */

import { useState, useEffect } from 'react'
import Link from 'next/link'
import AdminLayout from '@/components/admin/AdminLayout'

interface Export {
  id: string
  export_type: string
  export_name: string
  status: string
  requested_by: string
  requested_at: string
  completed_at: string | null
  file_path: string | null
  file_hash: string | null
  file_size_bytes: number | null
  total_controls: number | null
  total_evidence: number | null
  compliance_score: number | null
  error_message: string | null
}

interface Regulation {
  code: string
  name: string
}

const EXPORT_TYPES = [
  { value: 'full', label: 'Vollstaendiger Export', description: 'Alle Daten inkl. Regulations, Controls, Evidence, Risks' },
  { value: 'controls_only', label: 'Nur Controls', description: 'Control Catalogue mit Mappings' },
  { value: 'evidence_only', label: 'Nur Nachweise', description: 'Evidence-Dateien und Metadaten' },
]

const DOMAIN_OPTIONS = [
  { value: 'gov', label: 'Governance' },
  { value: 'priv', label: 'Datenschutz' },
  { value: 'iam', label: 'Identity & Access' },
  { value: 'crypto', label: 'Kryptografie' },
  { value: 'sdlc', label: 'Secure Dev' },
  { value: 'ops', label: 'Operations' },
  { value: 'ai', label: 'KI-spezifisch' },
  { value: 'cra', label: 'Supply Chain' },
  { value: 'aud', label: 'Audit' },
]

export default function ExportPage() {
  const [exports, setExports] = useState<Export[]>([])
  const [regulations, setRegulations] = useState<Regulation[]>([])
  const [loading, setLoading] = useState(true)
  const [generating, setGenerating] = useState(false)

  const [wizardStep, setWizardStep] = useState(1)
  const [exportType, setExportType] = useState('full')
  const [selectedRegulations, setSelectedRegulations] = useState<string[]>([])
  const [selectedDomains, setSelectedDomains] = useState<string[]>([])
  const [currentExport, setCurrentExport] = useState<Export | null>(null)

  const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000'

  useEffect(() => {
    loadData()
  }, [])

  const loadData = async () => {
    setLoading(true)
    try {
      const [exportsRes, regulationsRes] = await Promise.all([
        fetch(`${BACKEND_URL}/api/v1/compliance/exports`),
        fetch(`${BACKEND_URL}/api/v1/compliance/regulations`),
      ])

      if (exportsRes.ok) {
        const data = await exportsRes.json()
        setExports(data.exports || [])
      }
      if (regulationsRes.ok) {
        const data = await regulationsRes.json()
        setRegulations(data.regulations || [])
      }
    } catch (error) {
      console.error('Failed to load data:', error)
    } finally {
      setLoading(false)
    }
  }

  const startExport = async () => {
    setGenerating(true)
    try {
      const res = await fetch(`${BACKEND_URL}/api/v1/compliance/export`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          export_type: exportType,
          included_regulations: selectedRegulations.length > 0 ? selectedRegulations : null,
          included_domains: selectedDomains.length > 0 ? selectedDomains : null,
        }),
      })

      if (res.ok) {
        const exportData = await res.json()
        setCurrentExport(exportData)
        setWizardStep(4)
        loadData()
      } else {
        const error = await res.text()
        alert(`Export fehlgeschlagen: ${error}`)
      }
    } catch (error) {
      console.error('Export failed:', error)
      alert('Export fehlgeschlagen')
    } finally {
      setGenerating(false)
    }
  }

  const downloadExport = (exportId: string) => {
    window.open(`${BACKEND_URL}/api/v1/compliance/export/${exportId}/download`, '_blank')
  }

  const resetWizard = () => {
    setWizardStep(1)
    setExportType('full')
    setSelectedRegulations([])
    setSelectedDomains([])
    setCurrentExport(null)
  }

  const toggleRegulation = (code: string) => {
    setSelectedRegulations((prev) =>
      prev.includes(code) ? prev.filter((r) => r !== code) : [...prev, code]
    )
  }

  const toggleDomain = (domain: string) => {
    setSelectedDomains((prev) =>
      prev.includes(domain) ? prev.filter((d) => d !== domain) : [...prev, domain]
    )
  }

  const formatFileSize = (bytes: number | null) => {
    if (!bytes) return '-'
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  }

  const renderWizardSteps = () => (
    <div className="flex items-center justify-center mb-8">
      {[
        { num: 1, label: 'Typ' },
        { num: 2, label: 'Scope' },
        { num: 3, label: 'Bestaetigen' },
        { num: 4, label: 'Download' },
      ].map((step, idx) => (
        <div key={step.num} className="flex items-center">
          <div className={`flex items-center justify-center w-10 h-10 rounded-full font-medium ${
            wizardStep >= step.num
              ? 'bg-primary-600 text-white'
              : 'bg-slate-200 text-slate-500'
          }`}>
            {wizardStep > step.num ? (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            ) : (
              step.num
            )}
          </div>
          <span className={`ml-2 text-sm ${wizardStep >= step.num ? 'text-slate-900' : 'text-slate-500'}`}>
            {step.label}
          </span>
          {idx < 3 && (
            <div className={`w-16 h-0.5 mx-4 ${wizardStep > step.num ? 'bg-primary-600' : 'bg-slate-200'}`} />
          )}
        </div>
      ))}
    </div>
  )

  const renderStep1 = () => (
    <div className="space-y-4">
      <h3 className="text-lg font-semibold text-slate-900 mb-4">Export-Typ waehlen</h3>
      <div className="grid gap-4">
        {EXPORT_TYPES.map((type) => (
          <button
            key={type.value}
            onClick={() => setExportType(type.value)}
            className={`p-4 rounded-lg border-2 text-left transition-colors ${
              exportType === type.value
                ? 'border-primary-600 bg-primary-50'
                : 'border-slate-200 hover:border-slate-300'
            }`}
          >
            <div className="flex items-center gap-3">
              <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${
                exportType === type.value ? 'border-primary-600' : 'border-slate-300'
              }`}>
                {exportType === type.value && (
                  <div className="w-3 h-3 rounded-full bg-primary-600" />
                )}
              </div>
              <div>
                <p className="font-medium text-slate-900">{type.label}</p>
                <p className="text-sm text-slate-500">{type.description}</p>
              </div>
            </div>
          </button>
        ))}
      </div>
      <div className="flex justify-end pt-4">
        <button
          onClick={() => setWizardStep(2)}
          className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
        >
          Weiter
        </button>
      </div>
    </div>
  )

  const renderStep2 = () => (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold text-slate-900">Scope definieren (optional)</h3>

      {/* Regulations Filter */}
      <div>
        <h4 className="text-sm font-medium text-slate-700 mb-3">Verordnungen filtern</h4>
        <p className="text-sm text-slate-500 mb-3">Leer lassen fuer alle Verordnungen</p>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
          {regulations.map((reg) => (
            <button
              key={reg.code}
              onClick={() => toggleRegulation(reg.code)}
              className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
                selectedRegulations.includes(reg.code)
                  ? 'border-primary-600 bg-primary-50 text-primary-700'
                  : 'border-slate-200 text-slate-600 hover:border-slate-300'
              }`}
            >
              {reg.code}
            </button>
          ))}
        </div>
      </div>

      {/* Domains Filter */}
      <div>
        <h4 className="text-sm font-medium text-slate-700 mb-3">Domains filtern</h4>
        <p className="text-sm text-slate-500 mb-3">Leer lassen fuer alle Domains</p>
        <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
          {DOMAIN_OPTIONS.map((domain) => (
            <button
              key={domain.value}
              onClick={() => toggleDomain(domain.value)}
              className={`px-3 py-2 text-sm rounded-lg border transition-colors ${
                selectedDomains.includes(domain.value)
                  ? 'border-primary-600 bg-primary-50 text-primary-700'
                  : 'border-slate-200 text-slate-600 hover:border-slate-300'
              }`}
            >
              {domain.label}
            </button>
          ))}
        </div>
      </div>

      <div className="flex justify-between pt-4">
        <button
          onClick={() => setWizardStep(1)}
          className="px-6 py-2 text-slate-600 hover:text-slate-800"
        >
          Zurueck
        </button>
        <button
          onClick={() => setWizardStep(3)}
          className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
        >
          Weiter
        </button>
      </div>
    </div>
  )

  const renderStep3 = () => (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold text-slate-900">Export bestaetigen</h3>

      <div className="bg-slate-50 rounded-lg p-6 space-y-4">
        <div className="flex justify-between">
          <span className="text-slate-600">Export-Typ:</span>
          <span className="font-medium text-slate-900">
            {EXPORT_TYPES.find((t) => t.value === exportType)?.label}
          </span>
        </div>

        <div className="flex justify-between">
          <span className="text-slate-600">Verordnungen:</span>
          <span className="font-medium text-slate-900">
            {selectedRegulations.length > 0 ? selectedRegulations.join(', ') : 'Alle'}
          </span>
        </div>

        <div className="flex justify-between">
          <span className="text-slate-600">Domains:</span>
          <span className="font-medium text-slate-900">
            {selectedDomains.length > 0
              ? selectedDomains.map((d) => DOMAIN_OPTIONS.find((o) => o.value === d)?.label).join(', ')
              : 'Alle'}
          </span>
        </div>
      </div>

      <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
        <p className="text-sm text-yellow-800">
          Der Export kann je nach Datenmenge einige Sekunden dauern.
          Nach Abschluss koennen Sie die ZIP-Datei herunterladen.
        </p>
      </div>

      <div className="flex justify-between pt-4">
        <button
          onClick={() => setWizardStep(2)}
          className="px-6 py-2 text-slate-600 hover:text-slate-800"
        >
          Zurueck
        </button>
        <button
          onClick={startExport}
          disabled={generating}
          className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 flex items-center gap-2"
        >
          {generating && (
            <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
          )}
          {generating ? 'Generiere...' : 'Export starten'}
        </button>
      </div>
    </div>
  )

  const renderStep4 = () => (
    <div className="space-y-6 text-center">
      {currentExport?.status === 'completed' ? (
        <>
          <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto">
            <svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-slate-900">Export erfolgreich!</h3>

          <div className="bg-slate-50 rounded-lg p-6 text-left space-y-3">
            <div className="flex justify-between">
              <span className="text-slate-600">Compliance Score:</span>
              <span className="font-medium text-slate-900">{currentExport.compliance_score?.toFixed(1)}%</span>
            </div>
            <div className="flex justify-between">
              <span className="text-slate-600">Controls:</span>
              <span className="font-medium text-slate-900">{currentExport.total_controls}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-slate-600">Nachweise:</span>
              <span className="font-medium text-slate-900">{currentExport.total_evidence}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-slate-600">Dateigroesse:</span>
              <span className="font-medium text-slate-900">{formatFileSize(currentExport.file_size_bytes)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-slate-600">SHA-256:</span>
              <span className="font-mono text-xs text-slate-500 truncate max-w-xs">{currentExport.file_hash}</span>
            </div>
          </div>

          <div className="flex justify-center gap-4 pt-4">
            <button
              onClick={resetWizard}
              className="px-6 py-2 text-slate-600 hover:text-slate-800"
            >
              Neuer Export
            </button>
            <button
              onClick={() => downloadExport(currentExport.id)}
              className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 flex items-center gap-2"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
              ZIP herunterladen
            </button>
          </div>
        </>
      ) : (
        <>
          <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto">
            <svg className="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-slate-900">Export fehlgeschlagen</h3>
          <p className="text-slate-500">{currentExport?.error_message || 'Unbekannter Fehler'}</p>
          <button
            onClick={resetWizard}
            className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
          >
            Erneut versuchen
          </button>
        </>
      )}
    </div>
  )

  return (
    <AdminLayout title="Audit Export" description="Export fuer externe Pruefer">
      {/* Header */}
      <div className="flex flex-wrap items-center gap-4 mb-6">
        <Link
          href="/admin/compliance"
          className="text-sm text-slate-500 hover:text-slate-700 flex items-center gap-1"
        >
          <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>
          Zurueck
        </Link>
      </div>

      {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="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Wizard */}
          <div className="lg:col-span-2 bg-white rounded-xl shadow-sm border p-6">
            {renderWizardSteps()}

            {wizardStep === 1 && renderStep1()}
            {wizardStep === 2 && renderStep2()}
            {wizardStep === 3 && renderStep3()}
            {wizardStep === 4 && renderStep4()}
          </div>

          {/* Export History */}
          <div className="bg-white rounded-xl shadow-sm border p-6">
            <h3 className="text-lg font-semibold text-slate-900 mb-4">Letzte Exports</h3>

            {exports.length === 0 ? (
              <p className="text-slate-500 text-sm">Noch keine Exports vorhanden</p>
            ) : (
              <div className="space-y-3">
                {exports.slice(0, 10).map((exp) => (
                  <div key={exp.id} className="p-3 bg-slate-50 rounded-lg">
                    <div className="flex items-center justify-between mb-1">
                      <span className={`px-2 py-0.5 text-xs rounded-full ${
                        exp.status === 'completed' ? 'bg-green-100 text-green-700' :
                        exp.status === 'failed' ? 'bg-red-100 text-red-700' :
                        'bg-yellow-100 text-yellow-700'
                      }`}>
                        {exp.status}
                      </span>
                      <span className="text-xs text-slate-500">
                        {new Date(exp.requested_at).toLocaleDateString('de-DE')}
                      </span>
                    </div>
                    <p className="text-sm font-medium text-slate-900">{exp.export_name}</p>
                    <p className="text-xs text-slate-500">{exp.export_type} - {formatFileSize(exp.file_size_bytes)}</p>

                    {exp.status === 'completed' && (
                      <button
                        onClick={() => downloadExport(exp.id)}
                        className="mt-2 text-xs text-primary-600 hover:text-primary-700 font-medium"
                      >
                        Download
                      </button>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </AdminLayout>
  )
}
