'use client'

/**
 * Evidence Management Page
 *
 * Features:
 * - List evidence by control
 * - File upload
 * - URL/Link adding
 * - Evidence status tracking
 */

import { useState, useEffect, useRef, Suspense } from 'react'
import { useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { PagePurpose } from '@/components/common/PagePurpose'

interface Evidence {
  id: string
  control_id: string
  evidence_type: string
  title: string
  description: string
  artifact_path: string | null
  artifact_url: string | null
  artifact_hash: string | null
  file_size_bytes: number | null
  mime_type: string | null
  status: string
  source: string
  ci_job_id: string | null
  valid_from: string
  valid_until: string | null
  collected_at: string
}

interface Control {
  id: string
  control_id: string
  title: string
}

const EVIDENCE_TYPES = [
  { value: 'scan_report', label: 'Scan Report', icon: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z' },
  { value: 'policy_document', label: 'Policy Dokument', icon: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z' },
  { value: 'config_snapshot', label: 'Config Snapshot', icon: 'M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4' },
  { value: 'test_result', label: 'Test Ergebnis', icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' },
  { value: 'screenshot', label: 'Screenshot', icon: 'M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z' },
  { value: 'external_link', label: 'Externer Link', icon: 'M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14' },
  { value: 'manual_upload', label: 'Manueller Upload', icon: 'M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12' },
]

const STATUS_STYLES: Record<string, { bg: string; text: string; label: string }> = {
  valid: { bg: 'bg-green-100', text: 'text-green-700', label: 'Gueltig' },
  expired: { bg: 'bg-red-100', text: 'text-red-700', label: 'Abgelaufen' },
  pending: { bg: 'bg-yellow-100', text: 'text-yellow-700', label: 'Ausstehend' },
  failed: { bg: 'bg-red-100', text: 'text-red-700', label: 'Fehlgeschlagen' },
}

function EvidencePageContent({ initialControlId }: { initialControlId: string | null }) {
  const [evidence, setEvidence] = useState<Evidence[]>([])
  const [controls, setControls] = useState<Control[]>([])
  const [loading, setLoading] = useState(true)
  const [filterControlId, setFilterControlId] = useState(initialControlId || '')
  const [filterType, setFilterType] = useState('')

  const [uploadModalOpen, setUploadModalOpen] = useState(false)
  const [linkModalOpen, setLinkModalOpen] = useState(false)
  const [uploading, setUploading] = useState(false)

  const [newEvidence, setNewEvidence] = useState({
    control_id: initialControlId || '',
    evidence_type: 'manual_upload',
    title: '',
    description: '',
    artifact_url: '',
  })

  const fileInputRef = useRef<HTMLInputElement>(null)
  const [selectedFile, setSelectedFile] = useState<File | null>(null)

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

  const loadData = async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      if (filterControlId) params.append('control_id', filterControlId)
      if (filterType) params.append('evidence_type', filterType)

      const [evidenceRes, controlsRes] = await Promise.all([
        fetch(`/api/admin/compliance/evidence?${params}`),
        fetch(`/api/admin/compliance/controls`),
      ])

      if (evidenceRes.ok) {
        const data = await evidenceRes.json()
        setEvidence(data.evidence || [])
      }
      if (controlsRes.ok) {
        const data = await controlsRes.json()
        setControls(data.controls || [])
      }
    } catch (error) {
      console.error('Failed to load data:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleFileUpload = async () => {
    if (!selectedFile || !newEvidence.control_id || !newEvidence.title) {
      alert('Bitte alle Pflichtfelder ausfuellen')
      return
    }

    setUploading(true)
    try {
      const formData = new FormData()
      formData.append('file', selectedFile)

      const params = new URLSearchParams({
        control_id: newEvidence.control_id,
        evidence_type: newEvidence.evidence_type,
        title: newEvidence.title,
      })
      if (newEvidence.description) {
        params.append('description', newEvidence.description)
      }

      const res = await fetch(`/api/admin/compliance/evidence/upload?${params}`, {
        method: 'POST',
        body: formData,
      })

      if (res.ok) {
        setUploadModalOpen(false)
        resetForm()
        loadData()
      } else {
        const error = await res.text()
        alert(`Upload fehlgeschlagen: ${error}`)
      }
    } catch (error) {
      console.error('Upload failed:', error)
      alert('Upload fehlgeschlagen')
    } finally {
      setUploading(false)
    }
  }

  const handleLinkSubmit = async () => {
    if (!newEvidence.control_id || !newEvidence.title || !newEvidence.artifact_url) {
      alert('Bitte alle Pflichtfelder ausfuellen')
      return
    }

    setUploading(true)
    try {
      const res = await fetch(`/api/admin/compliance/evidence`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          control_id: newEvidence.control_id,
          evidence_type: 'external_link',
          title: newEvidence.title,
          description: newEvidence.description,
          artifact_url: newEvidence.artifact_url,
          source: 'manual',
        }),
      })

      if (res.ok) {
        setLinkModalOpen(false)
        resetForm()
        loadData()
      } else {
        const error = await res.text()
        alert(`Fehler: ${error}`)
      }
    } catch (error) {
      console.error('Failed to add link:', error)
      alert('Fehler beim Hinzufuegen')
    } finally {
      setUploading(false)
    }
  }

  const resetForm = () => {
    setNewEvidence({
      control_id: filterControlId || '',
      evidence_type: 'manual_upload',
      title: '',
      description: '',
      artifact_url: '',
    })
    setSelectedFile(null)
  }

  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 getControlTitle = (controlUuid: string) => {
    const control = controls.find((c) => c.id === controlUuid)
    return control?.control_id || controlUuid
  }

  // Statistics
  const stats = {
    total: evidence.length,
    valid: evidence.filter(e => e.status === 'valid').length,
    expired: evidence.filter(e => e.status === 'expired').length,
    pending: evidence.filter(e => e.status === 'pending').length,
    automated: evidence.filter(e => e.source === 'ci_pipeline').length,
  }

  return (
    <div className="min-h-screen bg-slate-50 p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Evidence Management</h1>
          <p className="text-slate-600">Nachweise & Artefakte</p>
        </div>
        <Link
          href="/compliance/hub"
          className="flex items-center gap-2 text-slate-600 hover:text-slate-800"
        >
          <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>
          Compliance Hub
        </Link>
      </div>

      {/* Page Purpose */}
      <PagePurpose
        title="Evidence Management"
        purpose="Verwalten Sie alle Nachweise und Artefakte, die die Einhaltung von Compliance-Anforderungen belegen. Jeder Control kann mit mehreren Nachweisen verknuepft werden - von automatischen Scan-Reports bis zu manuellen Dokumenten."
        audience={['CISO', 'DSB', 'Compliance Officer', 'Auditoren']}
        gdprArticles={['Art. 5(2) (Rechenschaftspflicht)', 'Art. 30 (Verzeichnis von Verarbeitungstaetigkeiten)']}
        architecture={{
          services: ['Python Backend (FastAPI)', 'compliance_evidence Modul'],
          databases: ['PostgreSQL (compliance_evidence Table)', 'MinIO (Datei-Storage)'],
        }}
        relatedPages={[
          { name: 'Controls', href: '/compliance/controls', description: 'Control-Katalog verwalten' },
          { name: 'Audit Checklist', href: '/compliance/audit-checklist', description: 'Anforderungen pruefen' },
        ]}
      />

      {/* Statistics Cards */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
        <div className="bg-white rounded-xl p-4 border border-slate-200">
          <p className="text-sm text-slate-500">Gesamt</p>
          <p className="text-2xl font-bold text-slate-900">{stats.total}</p>
        </div>
        <div className="bg-white rounded-xl p-4 border border-green-200">
          <p className="text-sm text-green-600">Gueltig</p>
          <p className="text-2xl font-bold text-green-700">{stats.valid}</p>
        </div>
        <div className="bg-white rounded-xl p-4 border border-red-200">
          <p className="text-sm text-red-600">Abgelaufen</p>
          <p className="text-2xl font-bold text-red-700">{stats.expired}</p>
        </div>
        <div className="bg-white rounded-xl p-4 border border-yellow-200">
          <p className="text-sm text-yellow-600">Ausstehend</p>
          <p className="text-2xl font-bold text-yellow-700">{stats.pending}</p>
        </div>
        <div className="bg-white rounded-xl p-4 border border-blue-200">
          <p className="text-sm text-blue-600">CI/CD</p>
          <p className="text-2xl font-bold text-blue-700">{stats.automated}</p>
        </div>
      </div>

      {/* Actions & Filters */}
      <div className="bg-white rounded-xl shadow-sm border p-4 mb-6">
        <div className="flex flex-wrap items-center gap-4">
          <select
            value={filterControlId}
            onChange={(e) => setFilterControlId(e.target.value)}
            className="px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
          >
            <option value="">Alle Controls</option>
            {controls.map((c) => (
              <option key={c.id} value={c.control_id}>{c.control_id} - {c.title}</option>
            ))}
          </select>

          <select
            value={filterType}
            onChange={(e) => setFilterType(e.target.value)}
            className="px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
          >
            <option value="">Alle Typen</option>
            {EVIDENCE_TYPES.map((t) => (
              <option key={t.value} value={t.value}>{t.label}</option>
            ))}
          </select>

          <div className="flex-1" />

          <button
            onClick={() => { resetForm(); setLinkModalOpen(true) }}
            className="px-4 py-2 border border-primary-600 text-primary-600 rounded-lg hover:bg-primary-50"
          >
            Link hinzufuegen
          </button>
          <button
            onClick={() => { resetForm(); setUploadModalOpen(true) }}
            className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
          >
            Datei hochladen
          </button>
        </div>
      </div>

      {/* Evidence List */}
      {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>
      ) : evidence.length === 0 ? (
        <div className="bg-white rounded-xl shadow-sm border p-12 text-center">
          <svg className="w-16 h-16 text-slate-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          <p className="text-slate-500 mb-4">Keine Nachweise gefunden</p>
          <button
            onClick={() => setUploadModalOpen(true)}
            className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700"
          >
            Ersten Nachweis hinzufuegen
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {evidence.map((ev) => {
            const statusStyle = STATUS_STYLES[ev.status] || STATUS_STYLES.pending
            return (
              <div key={ev.id} className="bg-white rounded-xl shadow-sm border p-4 hover:border-primary-300 transition-colors">
                <div className="flex items-start justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center">
                      <svg className="w-5 h-5 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={EVIDENCE_TYPES.find((t) => t.value === ev.evidence_type)?.icon || 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z'} />
                      </svg>
                    </div>
                    <span className={`px-2 py-0.5 text-xs rounded-full ${statusStyle.bg} ${statusStyle.text}`}>
                      {statusStyle.label}
                    </span>
                  </div>
                  <span className="text-xs text-slate-500 font-mono">{getControlTitle(ev.control_id)}</span>
                </div>

                <h4 className="font-medium text-slate-900 mb-1">{ev.title}</h4>
                {ev.description && (
                  <p className="text-sm text-slate-500 mb-3 line-clamp-2">{ev.description}</p>
                )}

                <div className="flex items-center justify-between text-xs text-slate-500 pt-3 border-t">
                  <span>{EVIDENCE_TYPES.find(t => t.value === ev.evidence_type)?.label || ev.evidence_type}</span>
                  <span>{formatFileSize(ev.file_size_bytes)}</span>
                </div>

                {ev.artifact_url && (
                  <a
                    href={ev.artifact_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mt-3 block text-sm text-primary-600 hover:text-primary-700 truncate"
                  >
                    {ev.artifact_url}
                  </a>
                )}

                <div className="mt-3 flex items-center justify-between text-xs text-slate-400">
                  <span>Erfasst: {new Date(ev.collected_at).toLocaleDateString('de-DE')}</span>
                  {ev.source === 'ci_pipeline' && (
                    <span className="bg-blue-50 text-blue-600 px-1.5 py-0.5 rounded">CI/CD</span>
                  )}
                </div>
              </div>
            )
          })}
        </div>
      )}

      {/* Upload Modal */}
      {uploadModalOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg">
            <div className="p-6 border-b">
              <h3 className="text-lg font-semibold text-slate-900">Datei hochladen</h3>
            </div>

            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Control *</label>
                <select
                  value={newEvidence.control_id}
                  onChange={(e) => setNewEvidence({ ...newEvidence, control_id: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
                >
                  <option value="">Control auswaehlen...</option>
                  {controls.map((c) => (
                    <option key={c.id} value={c.control_id}>{c.control_id} - {c.title}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Typ</label>
                <select
                  value={newEvidence.evidence_type}
                  onChange={(e) => setNewEvidence({ ...newEvidence, evidence_type: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
                >
                  {EVIDENCE_TYPES.filter((t) => t.value !== 'external_link').map((t) => (
                    <option key={t.value} value={t.value}>{t.label}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Titel *</label>
                <input
                  type="text"
                  value={newEvidence.title}
                  onChange={(e) => setNewEvidence({ ...newEvidence, title: e.target.value })}
                  placeholder="z.B. Semgrep Scan Report 2026-01"
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Beschreibung</label>
                <textarea
                  value={newEvidence.description}
                  onChange={(e) => setNewEvidence({ ...newEvidence, description: e.target.value })}
                  rows={2}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Datei *</label>
                <input
                  type="file"
                  ref={fileInputRef}
                  onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
                />
                {selectedFile && (
                  <p className="mt-1 text-sm text-slate-500">
                    {selectedFile.name} ({formatFileSize(selectedFile.size)})
                  </p>
                )}
              </div>
            </div>

            <div className="p-6 border-t bg-slate-50 flex justify-end gap-3">
              <button
                onClick={() => setUploadModalOpen(false)}
                className="px-4 py-2 text-slate-600 hover:text-slate-800"
                disabled={uploading}
              >
                Abbrechen
              </button>
              <button
                onClick={handleFileUpload}
                disabled={uploading}
                className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50"
              >
                {uploading ? 'Hochladen...' : 'Hochladen'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Link Modal */}
      {linkModalOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg">
            <div className="p-6 border-b">
              <h3 className="text-lg font-semibold text-slate-900">Link/Quelle hinzufuegen</h3>
            </div>

            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Control *</label>
                <select
                  value={newEvidence.control_id}
                  onChange={(e) => setNewEvidence({ ...newEvidence, control_id: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
                >
                  <option value="">Control auswaehlen...</option>
                  {controls.map((c) => (
                    <option key={c.id} value={c.control_id}>{c.control_id} - {c.title}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Titel *</label>
                <input
                  type="text"
                  value={newEvidence.title}
                  onChange={(e) => setNewEvidence({ ...newEvidence, title: e.target.value })}
                  placeholder="z.B. GitHub Branch Protection Settings"
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">URL *</label>
                <input
                  type="url"
                  value={newEvidence.artifact_url}
                  onChange={(e) => setNewEvidence({ ...newEvidence, artifact_url: e.target.value })}
                  placeholder="https://github.com/..."
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Beschreibung</label>
                <textarea
                  value={newEvidence.description}
                  onChange={(e) => setNewEvidence({ ...newEvidence, description: e.target.value })}
                  rows={2}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary-500"
                />
              </div>
            </div>

            <div className="p-6 border-t bg-slate-50 flex justify-end gap-3">
              <button
                onClick={() => setLinkModalOpen(false)}
                className="px-4 py-2 text-slate-600 hover:text-slate-800"
                disabled={uploading}
              >
                Abbrechen
              </button>
              <button
                onClick={handleLinkSubmit}
                disabled={uploading}
                className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50"
              >
                {uploading ? 'Speichern...' : 'Hinzufuegen'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

function EvidencePageWithParams() {
  const searchParams = useSearchParams()
  const initialControlId = searchParams.get('control')
  return <EvidencePageContent initialControlId={initialControlId} />
}

export default function EvidencePage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-slate-50 p-6 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600" />
      </div>
    }>
      <EvidencePageWithParams />
    </Suspense>
  )
}
