'use client'

import React, { useState, useRef } from 'react'
import { useSDK, ScreeningResult, SecurityIssue, SBOMComponent } from '@/lib/sdk'

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

function ScanProgress({ progress, status }: { progress: number; status: string }) {
  return (
    <div className="bg-white rounded-xl border border-gray-200 p-6">
      <div className="flex items-center gap-4">
        <div className="relative w-16 h-16">
          <svg className="w-16 h-16 transform -rotate-90">
            <circle cx="32" cy="32" r="28" stroke="#e5e7eb" strokeWidth="4" fill="none" />
            <circle
              cx="32"
              cy="32"
              r="28"
              stroke="#9333ea"
              strokeWidth="4"
              fill="none"
              strokeDasharray={`${progress * 1.76} 176`}
              strokeLinecap="round"
            />
          </svg>
          <span className="absolute inset-0 flex items-center justify-center text-sm font-bold text-gray-900">
            {progress}%
          </span>
        </div>
        <div>
          <h3 className="font-semibold text-gray-900">Scanning...</h3>
          <p className="text-sm text-gray-500">{status}</p>
        </div>
      </div>
      <div className="mt-4 h-2 bg-gray-100 rounded-full overflow-hidden">
        <div
          className="h-full bg-purple-600 rounded-full transition-all duration-500"
          style={{ width: `${progress}%` }}
        />
      </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 [isScanning, setIsScanning] = useState(false)
  const [scanProgress, setScanProgress] = useState(0)
  const [scanStatus, setScanStatus] = useState('')
  const [scanError, setScanError] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const startScan = async (file: File) => {
    setIsScanning(true)
    setScanProgress(0)
    setScanStatus('Initialisierung...')
    setScanError(null)

    // Show progress steps while API processes
    const progressInterval = setInterval(() => {
      setScanProgress(prev => {
        if (prev >= 90) return prev
        const step = Math.random() * 15 + 5
        const next = Math.min(prev + step, 90)
        const statuses = [
          'Abhaengigkeiten werden analysiert...',
          'SBOM wird generiert...',
          'Schwachstellenscan laeuft...',
          'OSV.dev Datenbank wird abgefragt...',
          'Lizenzpruefung...',
        ]
        setScanStatus(statuses[Math.min(Math.floor(next / 20), statuses.length - 1)])
        return next
      })
    }, 600)

    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(progressInterval)

      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()

      setScanProgress(100)
      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(progressInterval)
      console.error('Screening scan failed:', error)
      setScanError(error.message || 'Scan fehlgeschlagen')
      setScanProgress(0)
      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 progress={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 className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
              Zum Security Backlog hinzufügen
            </button>
          </div>
        </>
      )}
    </div>
  )
}
