'use client'

import React, { useState, useRef, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useSDK, ScreeningResult, SecurityIssue, SBOMComponent, BacklogItem } from '@/lib/sdk'

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

function ScanProgress({ status }: { status: string }) {
  return (
    <div className="bg-white rounded-xl border border-gray-200 p-6">
      <div className="flex items-center gap-4">
        <div className="w-10 h-10 border-4 border-gray-200 border-t-purple-600 rounded-full animate-spin flex-shrink-0" />
        <div>
          <h3 className="font-semibold text-gray-900">Scan läuft...</h3>
          <p className="text-sm text-gray-500">{status}</p>
        </div>
      </div>
      <div className="mt-4 h-1.5 bg-gray-100 rounded-full overflow-hidden">
        <div className="h-full bg-purple-600 rounded-full animate-pulse w-full" />
      </div>
    </div>
  )
}

function SBOMViewer({ components }: { components: SBOMComponent[] }) {
  return (
    <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
      <div className="px-6 py-4 border-b border-gray-200 bg-gray-50">
        <h3 className="font-semibold text-gray-900">Software Bill of Materials (SBOM)</h3>
        <p className="text-sm text-gray-500">{components.length} Komponenten gefunden</p>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Name</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Version</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Typ</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Lizenz</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Vulnerabilities</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {components.map(component => (
              <tr key={component.purl} className="hover:bg-gray-50">
                <td className="px-6 py-4">
                  <div className="font-medium text-gray-900">{component.name}</div>
                  <div className="text-xs text-gray-500 truncate max-w-xs">{component.purl}</div>
                </td>
                <td className="px-6 py-4 text-sm text-gray-500">{component.version}</td>
                <td className="px-6 py-4">
                  <span className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded-full">
                    {component.type}
                  </span>
                </td>
                <td className="px-6 py-4 text-sm text-gray-500">{component.licenses.join(', ')}</td>
                <td className="px-6 py-4">
                  {component.vulnerabilities.length > 0 ? (
                    <span className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded-full">
                      {component.vulnerabilities.length} gefunden
                    </span>
                  ) : (
                    <span className="px-2 py-1 text-xs bg-green-100 text-green-700 rounded-full">Keine</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}

function SecurityIssueCard({ issue }: { issue: SecurityIssue }) {
  const severityColors = {
    CRITICAL: 'bg-red-100 text-red-700 border-red-200',
    HIGH: 'bg-orange-100 text-orange-700 border-orange-200',
    MEDIUM: 'bg-yellow-100 text-yellow-700 border-yellow-200',
    LOW: 'bg-blue-100 text-blue-700 border-blue-200',
  }

  const statusColors = {
    OPEN: 'bg-red-50 text-red-700',
    IN_PROGRESS: 'bg-yellow-50 text-yellow-700',
    RESOLVED: 'bg-green-50 text-green-700',
    ACCEPTED: 'bg-gray-50 text-gray-700',
  }

  return (
    <div className={`bg-white rounded-xl border p-6 ${severityColors[issue.severity].split(' ')[2]}`}>
      <div className="flex items-start justify-between">
        <div className="flex items-start gap-4">
          <div
            className={`w-10 h-10 rounded-lg flex items-center justify-center ${severityColors[issue.severity]}`}
          >
            <svg className="w-5 h-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>
          <div>
            <h4 className="font-semibold text-gray-900">{issue.title}</h4>
            <p className="text-sm text-gray-500 mt-1">{issue.description}</p>
            <div className="flex items-center gap-3 mt-3">
              <span className={`px-2 py-1 text-xs rounded-full ${severityColors[issue.severity]}`}>
                {issue.severity}
              </span>
              {issue.cve && (
                <span className="text-xs text-gray-500">{issue.cve}</span>
              )}
              {issue.cvss && (
                <span className="text-xs text-gray-500">CVSS: {issue.cvss}</span>
              )}
            </div>
          </div>
        </div>
        <span className={`px-2 py-1 text-xs rounded-full ${statusColors[issue.status]}`}>
          {issue.status}
        </span>
      </div>
      <div className="mt-4 pt-4 border-t border-gray-100">
        <p className="text-sm text-gray-500">
          <span className="font-medium">Betroffene Komponente:</span> {issue.affectedComponent}
        </p>
        <p className="text-sm text-gray-500 mt-1">
          <span className="font-medium">Empfehlung:</span> {issue.remediation}
        </p>
      </div>
    </div>
  )
}

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

export default function ScreeningPage() {
  const { state, dispatch } = useSDK()
  const router = useRouter()
  const [isScanning, setIsScanning] = useState(false)
  const [scanStatus, setScanStatus] = useState('')
  const [scanError, setScanError] = useState<string | null>(null)
  const [scanHistory, setScanHistory] = useState<any[]>([])
  const [historyLoading, setHistoryLoading] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 5.2: Load scan history
  useEffect(() => {
    const loadHistory = async () => {
      setHistoryLoading(true)
      try {
        const response = await fetch('/api/sdk/v1/screening?tenant_id=default')
        if (response.ok) {
          const data = await response.json()
          setScanHistory(Array.isArray(data) ? data : data.items || [])
        }
      } catch (err) {
        console.error('Failed to load scan history:', err)
      } finally {
        setHistoryLoading(false)
      }
    }
    loadHistory()
  }, [state.screening])

  // 5.1: Add issues to security backlog
  const addToSecurityBacklog = () => {
    const issues = state.screening?.securityScan?.issues || []
    issues.forEach(issue => {
      const backlogItem: BacklogItem = {
        id: `backlog-${issue.id}`,
        title: issue.title,
        description: `${issue.description}\n\nBetroffene Komponente: ${issue.affectedComponent}\nEmpfehlung: ${issue.remediation}`,
        severity: issue.severity,
        securityIssueId: issue.id,
        status: 'OPEN',
        assignee: null,
        dueDate: null,
        createdAt: new Date(),
      }
      dispatch({ type: 'ADD_BACKLOG_ITEM', payload: backlogItem })
    })
    router.push('/sdk/security-backlog')
  }

  const startScan = async (file: File) => {
    setIsScanning(true)
    setScanStatus('Abhängigkeiten werden analysiert...')
    setScanError(null)

    // Rotate through honest status messages while backend processes
    const statusMessages = [
      'Abhängigkeiten werden analysiert...',
      'SBOM wird generiert...',
      'Schwachstellenscan läuft...',
      'OSV.dev Datenbank wird abgefragt...',
      'Lizenzprüfung...',
    ]
    let statusIdx = 0
    const statusInterval = setInterval(() => {
      statusIdx = (statusIdx + 1) % statusMessages.length
      setScanStatus(statusMessages[statusIdx])
    }, 2000)

    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('tenant_id', 'default')

      const response = await fetch('/api/sdk/v1/screening/scan', {
        method: 'POST',
        body: formData,
      })

      clearInterval(statusInterval)

      if (!response.ok) {
        const err = await response.json().catch(() => ({ error: 'Unknown error' }))
        throw new Error(err.details || err.error || `HTTP ${response.status}`)
      }

      const data = await response.json()

      setScanStatus('Abgeschlossen!')

      // Map backend response to ScreeningResult
      const issues: SecurityIssue[] = (data.issues || []).map((i: any) => ({
        id: i.id,
        severity: i.severity,
        title: i.title,
        description: i.description,
        cve: i.cve || null,
        cvss: i.cvss || null,
        affectedComponent: i.affected_component,
        remediation: i.remediation,
        status: i.status || 'OPEN',
      }))

      const components: SBOMComponent[] = (data.components || []).map((c: any) => ({
        name: c.name,
        version: c.version,
        type: c.type,
        purl: c.purl,
        licenses: c.licenses || [],
        vulnerabilities: c.vulnerabilities || [],
      }))

      const result: ScreeningResult = {
        id: data.id,
        status: 'COMPLETED',
        startedAt: data.started_at ? new Date(data.started_at) : new Date(),
        completedAt: data.completed_at ? new Date(data.completed_at) : new Date(),
        sbom: {
          format: data.sbom_format || 'CycloneDX',
          version: data.sbom_version || '1.5',
          components,
          dependencies: [],
          generatedAt: new Date(),
        },
        securityScan: {
          totalIssues: data.total_issues || issues.length,
          critical: data.critical_issues || 0,
          high: data.high_issues || 0,
          medium: data.medium_issues || 0,
          low: data.low_issues || 0,
          issues,
        },
        error: null,
      }

      dispatch({ type: 'SET_SCREENING', payload: result })
      issues.forEach(issue => {
        dispatch({ type: 'ADD_SECURITY_ISSUE', payload: issue })
      })
    } catch (error: any) {
      clearInterval(statusInterval)
      console.error('Screening scan failed:', error)
      setScanError(error.message || 'Scan fehlgeschlagen')
      setScanStatus('')
    } finally {
      setIsScanning(false)
    }
  }

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      startScan(file)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">System Screening</h1>
        <p className="mt-1 text-gray-500">
          Generieren Sie ein SBOM und scannen Sie Ihr System auf Sicherheitslücken
        </p>
      </div>

      {/* Scan Input */}
      {!state.screening && !isScanning && (
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h3 className="font-semibold text-gray-900 mb-4">Abhaengigkeiten scannen</h3>
          <p className="text-sm text-gray-500 mb-4">
            Laden Sie eine Abhaengigkeitsdatei hoch, um ein SBOM zu generieren und Schwachstellen zu erkennen.
          </p>
          <input
            ref={fileInputRef}
            type="file"
            accept=".json,.txt,.lock"
            onChange={handleFileSelect}
            className="hidden"
          />
          <div className="flex gap-4">
            <button
              onClick={() => fileInputRef.current?.click()}
              className="px-6 py-2 bg-purple-600 text-white rounded-lg font-medium hover:bg-purple-700 transition-colors"
            >
              Datei auswaehlen & scannen
            </button>
          </div>
          <p className="mt-2 text-sm text-gray-500">
            Unterstuetzte Formate: package-lock.json, requirements.txt, yarn.lock
          </p>
          {scanError && (
            <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
              {scanError}
            </div>
          )}
        </div>
      )}

      {/* Scan Progress */}
      {isScanning && <ScanProgress status={scanStatus} />}

      {/* Results */}
      {state.screening && state.screening.status === 'COMPLETED' && (
        <>
          {/* Summary */}
          <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">Komponenten</div>
              <div className="text-3xl font-bold text-gray-900">
                {state.screening.sbom?.components.length || 0}
              </div>
            </div>
            <div className="bg-white rounded-xl border border-red-200 p-6">
              <div className="text-sm text-red-600">Kritisch</div>
              <div className="text-3xl font-bold text-red-600">
                {state.screening.securityScan?.critical || 0}
              </div>
            </div>
            <div className="bg-white rounded-xl border border-orange-200 p-6">
              <div className="text-sm text-orange-600">Hoch</div>
              <div className="text-3xl font-bold text-orange-600">
                {state.screening.securityScan?.high || 0}
              </div>
            </div>
            <div className="bg-white rounded-xl border border-yellow-200 p-6">
              <div className="text-sm text-yellow-600">Mittel</div>
              <div className="text-3xl font-bold text-yellow-600">
                {state.screening.securityScan?.medium || 0}
              </div>
            </div>
          </div>

          {/* SBOM */}
          {state.screening.sbom && <SBOMViewer components={state.screening.sbom.components} />}

          {/* Security Issues */}
          <div>
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Sicherheitsprobleme</h3>
            <div className="space-y-4">
              {state.screening.securityScan?.issues.map(issue => (
                <SecurityIssueCard key={issue.id} issue={issue} />
              ))}
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center gap-4">
            <button
              onClick={() => dispatch({ type: 'SET_SCREENING', payload: null as any })}
              className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
            >
              Neuen Scan starten
            </button>
            <button
              onClick={addToSecurityBacklog}
              className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
            >
              Zum Security Backlog hinzufuegen
            </button>
          </div>
        </>
      )}

      {/* Scan-Verlauf */}
      {scanHistory.length > 0 && (
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-gray-200 bg-gray-50">
            <h3 className="font-semibold text-gray-900">Scan-Verlauf</h3>
            <p className="text-sm text-gray-500">{scanHistory.length} fruehere Scans</p>
          </div>
          <div className="divide-y divide-gray-100">
            {scanHistory.map((scan: any, idx: number) => (
              <div key={scan.id || idx} className="px-6 py-4 flex items-center justify-between hover:bg-gray-50">
                <div>
                  <p className="text-sm font-medium text-gray-900">
                    Scan #{scan.id?.slice(0, 8) || idx + 1}
                  </p>
                  <p className="text-xs text-gray-500">
                    {scan.completed_at ? new Date(scan.completed_at).toLocaleString('de-DE') : 'Unbekannt'}
                  </p>
                </div>
                <div className="flex items-center gap-3">
                  <span className="text-xs text-gray-500">
                    {scan.total_issues || 0} Issues
                  </span>
                  <span className={`px-2 py-1 text-xs rounded-full ${
                    (scan.critical_issues || 0) > 0
                      ? 'bg-red-100 text-red-700'
                      : 'bg-green-100 text-green-700'
                  }`}>
                    {(scan.critical_issues || 0) > 0 ? `${scan.critical_issues} Kritisch` : 'Keine kritischen'}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      {historyLoading && (
        <div className="text-center py-4 text-sm text-gray-500">Scan-Verlauf wird geladen...</div>
      )}
    </div>
  )
}
