'use client'

/**
 * Evidence Management Page
 */

import { useState, useEffect, Suspense } from 'react'
import { useSearchParams } from 'next/navigation'
import Link from 'next/link'
import AdminLayout from '@/components/admin/AdminLayout'
import { UploadModal, LinkModal } from './_components/EvidenceModals'
import { EvidenceCard } from './_components/EvidenceCard'

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_TYPE_OPTIONS = [
  { value: 'scan_report', label: 'Scan Report' },
  { value: 'policy_document', label: 'Policy Dokument' },
  { value: 'config_snapshot', label: 'Config Snapshot' },
  { value: 'test_result', label: 'Test Ergebnis' },
  { value: 'screenshot', label: 'Screenshot' },
  { value: 'external_link', label: 'Externer Link' },
  { value: 'manual_upload', label: 'Manueller Upload' },
]

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 BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000'

  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(`${BACKEND_URL}/api/v1/compliance/evidence?${params}`),
        fetch(`${BACKEND_URL}/api/v1/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 resetForm = () => { setNewEvidence({ control_id: filterControlId || '', evidence_type: 'manual_upload', title: '', description: '', artifact_url: '' }) }

  const handleFileUpload = async (file: File) => {
    if (!newEvidence.control_id || !newEvidence.title) { alert('Bitte alle Pflichtfelder ausfuellen'); return }
    setUploading(true)
    try {
      const formData = new FormData(); formData.append('file', file)
      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(`${BACKEND_URL}/api/v1/compliance/evidence/upload?${params}`, { method: 'POST', body: formData })
      if (res.ok) { setUploadModalOpen(false); resetForm(); loadData() } else { alert(`Upload fehlgeschlagen: ${await res.text()}`) }
    } catch { 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(`${BACKEND_URL}/api/v1/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 { alert(`Fehler: ${await res.text()}`) }
    } catch { alert('Fehler beim Hinzufuegen') } finally { setUploading(false) }
  }

  const getControlTitle = (controlUuid: string) => controls.find((c) => c.id === controlUuid)?.control_id || controlUuid

  return (
    <AdminLayout title="Evidence Management" description="Nachweise & Artefakte">
      <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 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 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_TYPE_OPTIONS.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
          </select>
          <span className="text-sm text-slate-500">{evidence.length} Nachweise</span>
        </div>
      </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>
      ) : 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) => <EvidenceCard key={ev.id} evidence={ev} controlTitle={getControlTitle(ev.control_id)} />)}
        </div>
      )}

      {uploadModalOpen && <UploadModal controls={controls} newEvidence={newEvidence} setNewEvidence={setNewEvidence} uploading={uploading} onUpload={handleFileUpload} onClose={() => setUploadModalOpen(false)} />}
      {linkModalOpen && <LinkModal controls={controls} newEvidence={newEvidence} setNewEvidence={setNewEvidence} uploading={uploading} onSubmit={handleLinkSubmit} onClose={() => setLinkModalOpen(false)} />}
    </AdminLayout>
  )
}

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

export default function EvidencePage() {
  return (
    <Suspense fallback={<AdminLayout title="Evidence Management" description="Nachweise & Artefakte"><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></AdminLayout>}>
      <EvidencePageWithParams />
    </Suspense>
  )
}
