'use client'

import React, { useState, useEffect } from 'react'
import { useSDK, Evidence as SDKEvidence, EvidenceType } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'

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

type DisplayEvidenceType = 'document' | 'screenshot' | 'log' | 'audit-report' | 'certificate'
type DisplayFormat = 'pdf' | 'image' | 'text' | 'json'
type DisplayStatus = 'valid' | 'expired' | 'pending-review'

interface DisplayEvidence {
  id: string
  name: string
  description: string
  displayType: DisplayEvidenceType
  format: DisplayFormat
  controlId: string
  linkedRequirements: string[]
  linkedControls: string[]
  uploadedBy: string
  uploadedAt: Date
  validFrom: Date
  validUntil: Date | null
  status: DisplayStatus
  fileSize: string
  fileUrl: string | null
}

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

function mapEvidenceTypeToDisplay(type: EvidenceType): DisplayEvidenceType {
  switch (type) {
    case 'DOCUMENT': return 'document'
    case 'SCREENSHOT': return 'screenshot'
    case 'LOG': return 'log'
    case 'CERTIFICATE': return 'certificate'
    case 'AUDIT_REPORT': return 'audit-report'
    default: return 'document'
  }
}

function mapDisplayTypeToEvidence(type: DisplayEvidenceType): EvidenceType {
  switch (type) {
    case 'document': return 'DOCUMENT'
    case 'screenshot': return 'SCREENSHOT'
    case 'log': return 'LOG'
    case 'certificate': return 'CERTIFICATE'
    case 'audit-report': return 'AUDIT_REPORT'
    default: return 'DOCUMENT'
  }
}

function getEvidenceStatus(validUntil: Date | null): DisplayStatus {
  if (!validUntil) return 'pending-review'
  const now = new Date()
  if (validUntil < now) return 'expired'
  return 'valid'
}

// =============================================================================
// EVIDENCE TEMPLATES
// =============================================================================

interface EvidenceTemplate {
  id: string
  name: string
  description: string
  type: EvidenceType
  displayType: DisplayEvidenceType
  format: DisplayFormat
  controlId: string
  linkedRequirements: string[]
  linkedControls: string[]
  uploadedBy: string
  validityDays: number
  fileSize: string
}

const evidenceTemplates: EvidenceTemplate[] = [
  {
    id: 'ev-dse-001',
    name: 'Datenschutzerklaerung v2.3',
    description: 'Aktuelle Datenschutzerklaerung fuer Website und App',
    type: 'DOCUMENT',
    displayType: 'document',
    format: 'pdf',
    controlId: 'ctrl-org-001',
    linkedRequirements: ['req-gdpr-13', 'req-gdpr-14'],
    linkedControls: ['ctrl-org-001'],
    uploadedBy: 'DSB',
    validityDays: 365,
    fileSize: '245 KB',
  },
  {
    id: 'ev-pentest-001',
    name: 'Penetrationstest Report Q4/2024',
    description: 'Externer Penetrationstest durch Security-Partner',
    type: 'AUDIT_REPORT',
    displayType: 'audit-report',
    format: 'pdf',
    controlId: 'ctrl-tom-001',
    linkedRequirements: ['req-gdpr-32', 'req-iso-a12'],
    linkedControls: ['ctrl-tom-001', 'ctrl-tom-002', 'ctrl-det-001'],
    uploadedBy: 'IT Security Team',
    validityDays: 365,
    fileSize: '2.1 MB',
  },
  {
    id: 'ev-iso-cert',
    name: 'ISO 27001 Zertifikat',
    description: 'Zertifizierung des ISMS',
    type: 'CERTIFICATE',
    displayType: 'certificate',
    format: 'pdf',
    controlId: 'ctrl-tom-001',
    linkedRequirements: ['req-iso-4.1', 'req-iso-5.1'],
    linkedControls: [],
    uploadedBy: 'QM Abteilung',
    validityDays: 365,
    fileSize: '156 KB',
  },
  {
    id: 'ev-schulung-001',
    name: 'Schulungsnachweis Datenschutz 2024',
    description: 'Teilnehmerliste und Schulungsinhalt',
    type: 'DOCUMENT',
    displayType: 'document',
    format: 'pdf',
    controlId: 'ctrl-org-001',
    linkedRequirements: ['req-gdpr-39'],
    linkedControls: ['ctrl-org-001'],
    uploadedBy: 'HR Team',
    validityDays: 365,
    fileSize: '890 KB',
  },
  {
    id: 'ev-rbac-001',
    name: 'Access Control Screenshot',
    description: 'Nachweis der RBAC-Konfiguration',
    type: 'SCREENSHOT',
    displayType: 'screenshot',
    format: 'image',
    controlId: 'ctrl-tom-001',
    linkedRequirements: ['req-gdpr-32'],
    linkedControls: ['ctrl-tom-001'],
    uploadedBy: 'Admin',
    validityDays: 0,
    fileSize: '1.2 MB',
  },
  {
    id: 'ev-log-001',
    name: 'Audit Log Export',
    description: 'Monatlicher Audit-Log Export',
    type: 'LOG',
    displayType: 'log',
    format: 'json',
    controlId: 'ctrl-det-001',
    linkedRequirements: ['req-gdpr-32'],
    linkedControls: ['ctrl-det-001'],
    uploadedBy: 'System',
    validityDays: 90,
    fileSize: '4.5 MB',
  },
]

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

function EvidenceCard({ evidence, onDelete }: { evidence: DisplayEvidence; onDelete: () => void }) {
  const typeIcons = {
    document: (
      <svg className="w-6 h-6" 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>
    ),
    screenshot: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="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" />
      </svg>
    ),
    log: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
      </svg>
    ),
    'audit-report': (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 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>
    ),
    certificate: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" />
      </svg>
    ),
  }

  const statusColors = {
    valid: 'bg-green-100 text-green-700 border-green-200',
    expired: 'bg-red-100 text-red-700 border-red-200',
    'pending-review': 'bg-yellow-100 text-yellow-700 border-yellow-200',
  }

  const statusLabels = {
    valid: 'Gueltig',
    expired: 'Abgelaufen',
    'pending-review': 'Pruefung ausstehend',
  }

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${
      evidence.status === 'expired' ? 'border-red-200' :
      evidence.status === 'pending-review' ? 'border-yellow-200' : 'border-gray-200'
    }`}>
      <div className="flex items-start gap-4">
        <div className={`w-12 h-12 rounded-lg flex items-center justify-center ${
          evidence.displayType === 'certificate' ? 'bg-yellow-100 text-yellow-600' :
          evidence.displayType === 'audit-report' ? 'bg-purple-100 text-purple-600' :
          evidence.displayType === 'screenshot' ? 'bg-blue-100 text-blue-600' :
          evidence.displayType === 'log' ? 'bg-green-100 text-green-600' :
          'bg-gray-100 text-gray-600'
        }`}>
          {typeIcons[evidence.displayType]}
        </div>
        <div className="flex-1">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold text-gray-900">{evidence.name}</h3>
            <span className={`px-3 py-1 text-xs rounded-full ${statusColors[evidence.status]}`}>
              {statusLabels[evidence.status]}
            </span>
          </div>
          <p className="text-sm text-gray-500 mt-1">{evidence.description}</p>

          <div className="mt-3 flex items-center gap-4 text-sm text-gray-500">
            <span>Hochgeladen: {evidence.uploadedAt.toLocaleDateString('de-DE')}</span>
            {evidence.validUntil && (
              <span className={evidence.status === 'expired' ? 'text-red-600' : ''}>
                Gueltig bis: {evidence.validUntil.toLocaleDateString('de-DE')}
              </span>
            )}
            <span>{evidence.fileSize}</span>
          </div>

          <div className="mt-3 flex items-center gap-2 flex-wrap">
            {evidence.linkedRequirements.map(req => (
              <span key={req} className="px-2 py-0.5 text-xs bg-blue-50 text-blue-600 rounded">
                {req}
              </span>
            ))}
            {evidence.linkedControls.map(ctrl => (
              <span key={ctrl} className="px-2 py-0.5 text-xs bg-green-50 text-green-600 rounded">
                {ctrl}
              </span>
            ))}
          </div>
        </div>
      </div>

      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between">
        <span className="text-sm text-gray-500">Hochgeladen von: {evidence.uploadedBy}</span>
        <div className="flex items-center gap-2">
          <button className="px-3 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            Anzeigen
          </button>
          <button className="px-3 py-1 text-sm text-purple-600 hover:bg-purple-50 rounded-lg transition-colors">
            Herunterladen
          </button>
          <button
            onClick={onDelete}
            className="px-3 py-1 text-sm text-red-600 hover:bg-red-50 rounded-lg transition-colors"
          >
            Loeschen
          </button>
        </div>
      </div>
    </div>
  )
}

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

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

  // Load evidence based on controls when controls exist
  useEffect(() => {
    if (state.controls.length > 0 && state.evidence.length === 0) {
      // Add relevant evidence based on controls
      const relevantEvidence = evidenceTemplates.filter(e =>
        state.controls.some(c => c.id === e.controlId || e.linkedControls.includes(c.id))
      )

      const now = new Date()
      relevantEvidence.forEach(template => {
        const validFrom = new Date(now)
        validFrom.setMonth(validFrom.getMonth() - 1) // Uploaded 1 month ago

        const validUntil = template.validityDays > 0
          ? new Date(validFrom.getTime() + template.validityDays * 24 * 60 * 60 * 1000)
          : null

        const sdkEvidence: SDKEvidence = {
          id: template.id,
          controlId: template.controlId,
          type: template.type,
          name: template.name,
          description: template.description,
          fileUrl: null,
          validFrom,
          validUntil,
          uploadedBy: template.uploadedBy,
          uploadedAt: validFrom,
        }
        dispatch({ type: 'ADD_EVIDENCE', payload: sdkEvidence })
      })
    }
  }, [state.controls, state.evidence.length, dispatch])

  // Convert SDK evidence to display evidence
  const displayEvidence: DisplayEvidence[] = state.evidence.map(ev => {
    const template = evidenceTemplates.find(t => t.id === ev.id)

    return {
      id: ev.id,
      name: ev.name,
      description: ev.description,
      displayType: mapEvidenceTypeToDisplay(ev.type),
      format: template?.format || 'pdf',
      controlId: ev.controlId,
      linkedRequirements: template?.linkedRequirements || [],
      linkedControls: template?.linkedControls || [ev.controlId],
      uploadedBy: ev.uploadedBy,
      uploadedAt: ev.uploadedAt,
      validFrom: ev.validFrom,
      validUntil: ev.validUntil,
      status: getEvidenceStatus(ev.validUntil),
      fileSize: template?.fileSize || 'Unbekannt',
      fileUrl: ev.fileUrl,
    }
  })

  const filteredEvidence = filter === 'all'
    ? displayEvidence
    : displayEvidence.filter(e => e.status === filter || e.displayType === filter)

  const validCount = displayEvidence.filter(e => e.status === 'valid').length
  const expiredCount = displayEvidence.filter(e => e.status === 'expired').length
  const pendingCount = displayEvidence.filter(e => e.status === 'pending-review').length

  const handleDelete = (evidenceId: string) => {
    if (confirm('Moechten Sie diesen Nachweis wirklich loeschen?')) {
      dispatch({ type: 'DELETE_EVIDENCE', payload: evidenceId })
    }
  }

  const stepInfo = STEP_EXPLANATIONS['evidence']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="evidence"
        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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
          </svg>
          Nachweis hochladen
        </button>
      </StepHeader>

      {/* Controls Alert */}
      {state.controls.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 Kontrollen definiert</h4>
              <p className="text-sm text-amber-700 mt-1">
                Bitte definieren Sie zuerst Kontrollen, um die zugehoerigen Nachweise 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">{displayEvidence.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Gueltig</div>
          <div className="text-3xl font-bold text-green-600">{validCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-red-200 p-6">
          <div className="text-sm text-red-600">Abgelaufen</div>
          <div className="text-3xl font-bold text-red-600">{expiredCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-6">
          <div className="text-sm text-yellow-600">Pruefung ausstehend</div>
          <div className="text-3xl font-bold text-yellow-600">{pendingCount}</div>
        </div>
      </div>

      {/* Filter */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'valid', 'expired', 'pending-review', 'document', 'certificate', 'audit-report'].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 === 'valid' ? 'Gueltig' :
             f === 'expired' ? 'Abgelaufen' :
             f === 'pending-review' ? 'Ausstehend' :
             f === 'document' ? 'Dokumente' :
             f === 'certificate' ? 'Zertifikate' : 'Audit-Berichte'}
          </button>
        ))}
      </div>

      {/* Evidence List */}
      <div className="space-y-4">
        {filteredEvidence.map(ev => (
          <EvidenceCard
            key={ev.id}
            evidence={ev}
            onDelete={() => handleDelete(ev.id)}
          />
        ))}
      </div>

      {filteredEvidence.length === 0 && state.controls.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 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>
          <h3 className="text-lg font-semibold text-gray-900">Keine Nachweise gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an oder laden Sie neue Nachweise hoch.</p>
        </div>
      )}
    </div>
  )
}
