'use client'

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

// =============================================================================
// MOCK DATA
// =============================================================================

const mockSBOMComponents: SBOMComponent[] = [
  {
    name: 'react',
    version: '18.3.0',
    type: 'library',
    purl: 'pkg:npm/react@18.3.0',
    licenses: ['MIT'],
    vulnerabilities: [],
  },
  {
    name: 'next',
    version: '15.1.0',
    type: 'framework',
    purl: 'pkg:npm/next@15.1.0',
    licenses: ['MIT'],
    vulnerabilities: [],
  },
  {
    name: 'lodash',
    version: '4.17.21',
    type: 'library',
    purl: 'pkg:npm/lodash@4.17.21',
    licenses: ['MIT'],
    vulnerabilities: [
      {
        id: 'CVE-2021-23337',
        cve: 'CVE-2021-23337',
        severity: 'HIGH',
        title: 'Prototype Pollution',
        description: 'Lodash versions prior to 4.17.21 are vulnerable to Command Injection via the template function.',
        cvss: 7.2,
        fixedIn: '4.17.21',
      },
    ],
  },
]

const mockSecurityIssues: SecurityIssue[] = [
  {
    id: 'issue-1',
    severity: 'CRITICAL',
    title: 'SQL Injection Vulnerability',
    description: 'Unvalidated user input in database queries',
    cve: 'CVE-2024-12345',
    cvss: 9.8,
    affectedComponent: 'database-connector',
    remediation: 'Use parameterized queries',
    status: 'OPEN',
  },
  {
    id: 'issue-2',
    severity: 'HIGH',
    title: 'Cross-Site Scripting (XSS)',
    description: 'Reflected XSS in search functionality',
    cve: 'CVE-2024-12346',
    cvss: 7.5,
    affectedComponent: 'search-module',
    remediation: 'Sanitize and encode user input',
    status: 'IN_PROGRESS',
  },
  {
    id: 'issue-3',
    severity: 'MEDIUM',
    title: 'Insecure Cookie Configuration',
    description: 'Session cookies missing Secure and HttpOnly flags',
    cve: null,
    cvss: 5.3,
    affectedComponent: 'auth-service',
    remediation: 'Set Secure and HttpOnly flags on cookies',
    status: 'OPEN',
  },
]

// =============================================================================
// 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 [repositoryUrl, setRepositoryUrl] = useState('')

  const startScan = async () => {
    if (!repositoryUrl) return

    setIsScanning(true)
    setScanProgress(0)
    setScanStatus('Initialisierung...')

    // Simulate scan progress
    const steps = [
      { progress: 10, status: 'Repository wird geklont...' },
      { progress: 25, status: 'Abhängigkeiten werden analysiert...' },
      { progress: 40, status: 'SBOM wird generiert...' },
      { progress: 60, status: 'Schwachstellenscan läuft...' },
      { progress: 80, status: 'Lizenzprüfung...' },
      { progress: 95, status: 'Bericht wird erstellt...' },
      { progress: 100, status: 'Abgeschlossen!' },
    ]

    for (const step of steps) {
      await new Promise(r => setTimeout(r, 800))
      setScanProgress(step.progress)
      setScanStatus(step.status)
    }

    // Set mock results
    const result: ScreeningResult = {
      id: `scan-${Date.now()}`,
      status: 'COMPLETED',
      startedAt: new Date(Date.now() - 30000),
      completedAt: new Date(),
      sbom: {
        format: 'CycloneDX',
        version: '1.5',
        components: mockSBOMComponents,
        dependencies: [],
        generatedAt: new Date(),
      },
      securityScan: {
        totalIssues: mockSecurityIssues.length,
        critical: mockSecurityIssues.filter(i => i.severity === 'CRITICAL').length,
        high: mockSecurityIssues.filter(i => i.severity === 'HIGH').length,
        medium: mockSecurityIssues.filter(i => i.severity === 'MEDIUM').length,
        low: mockSecurityIssues.filter(i => i.severity === 'LOW').length,
        issues: mockSecurityIssues,
      },
      error: null,
    }

    dispatch({ type: 'SET_SCREENING', payload: result })
    mockSecurityIssues.forEach(issue => {
      dispatch({ type: 'ADD_SECURITY_ISSUE', payload: issue })
    })

    setIsScanning(false)
  }

  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">Repository scannen</h3>
          <div className="flex gap-4">
            <input
              type="text"
              value={repositoryUrl}
              onChange={e => setRepositoryUrl(e.target.value)}
              placeholder="https://github.com/organization/repository"
              className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            />
            <button
              onClick={startScan}
              disabled={!repositoryUrl}
              className={`px-6 py-2 rounded-lg font-medium transition-colors ${
                repositoryUrl
                  ? 'bg-purple-600 text-white hover:bg-purple-700'
                  : 'bg-gray-200 text-gray-400 cursor-not-allowed'
              }`}
            >
              Scan starten
            </button>
          </div>
          <p className="mt-2 text-sm text-gray-500">
            Unterstützte Formate: Git URL, GitHub, GitLab, Bitbucket
          </p>
        </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>
  )
}
