'use client'

import { useState, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { useSDK } from '@/lib/sdk'
import type { ImportedDocument, ImportedDocumentType, GapAnalysis, GapItem } from '@/lib/sdk/types'

// =============================================================================
// DOCUMENT TYPE OPTIONS
// =============================================================================

const DOCUMENT_TYPES: { value: ImportedDocumentType; label: string; icon: string }[] = [
  { value: 'DSFA', label: 'Datenschutz-Folgenabschaetzung (DSFA)', icon: '📄' },
  { value: 'TOM', label: 'Technisch-organisatorische Massnahmen (TOMs)', icon: '🔒' },
  { value: 'VVT', label: 'Verarbeitungsverzeichnis (VVT)', icon: '📊' },
  { value: 'AGB', label: 'Allgemeine Geschaeftsbedingungen (AGB)', icon: '📜' },
  { value: 'PRIVACY_POLICY', label: 'Datenschutzerklaerung', icon: '🔐' },
  { value: 'COOKIE_POLICY', label: 'Cookie-Richtlinie', icon: '🍪' },
  { value: 'RISK_ASSESSMENT', label: 'Risikobewertung', icon: '⚠️' },
  { value: 'AUDIT_REPORT', label: 'Audit-Bericht', icon: '✅' },
  { value: 'OTHER', label: 'Sonstiges Dokument', icon: '📎' },
]

// =============================================================================
// UPLOAD ZONE
// =============================================================================

interface UploadedFile {
  id: string
  file: File
  type: ImportedDocumentType
  status: 'pending' | 'uploading' | 'analyzing' | 'complete' | 'error'
  progress: number
  error?: string
}

function UploadZone({
  onFilesAdded,
  isDisabled,
}: {
  onFilesAdded: (files: File[]) => void
  isDisabled: boolean
}) {
  const [isDragging, setIsDragging] = useState(false)

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    if (!isDisabled) setIsDragging(true)
  }, [isDisabled])

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
  }, [])

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault()
      setIsDragging(false)
      if (isDisabled) return

      const files = Array.from(e.dataTransfer.files).filter(
        f => f.type === 'application/pdf' || f.type.startsWith('image/')
      )
      if (files.length > 0) {
        onFilesAdded(files)
      }
    },
    [onFilesAdded, isDisabled]
  )

  const handleFileSelect = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files && !isDisabled) {
        const files = Array.from(e.target.files)
        onFilesAdded(files)
      }
    },
    [onFilesAdded, isDisabled]
  )

  return (
    <div
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
      className={`relative border-2 border-dashed rounded-xl p-12 text-center transition-all ${
        isDisabled
          ? 'border-gray-200 bg-gray-50 cursor-not-allowed'
          : isDragging
          ? 'border-purple-500 bg-purple-50'
          : 'border-gray-300 hover:border-purple-400 hover:bg-purple-50/50 cursor-pointer'
      }`}
    >
      <input
        type="file"
        accept=".pdf,image/*"
        multiple
        onChange={handleFileSelect}
        disabled={isDisabled}
        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
      />

      <div className="flex flex-col items-center gap-4">
        <div className={`w-16 h-16 rounded-full flex items-center justify-center ${isDragging ? 'bg-purple-100' : 'bg-gray-100'}`}>
          <svg
            className={`w-8 h-8 ${isDragging ? 'text-purple-600' : 'text-gray-400'}`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
            />
          </svg>
        </div>

        <div>
          <p className="text-lg font-medium text-gray-900">
            {isDragging ? 'Dateien hier ablegen' : 'Dokumente hochladen'}
          </p>
          <p className="mt-1 text-sm text-gray-500">
            Ziehen Sie PDF-Dateien hierher oder klicken Sie zum Auswaehlen
          </p>
        </div>

        <div className="flex items-center gap-2 text-xs text-gray-400">
          <span>Unterstuetzte Formate:</span>
          <span className="px-2 py-0.5 bg-gray-100 rounded">PDF</span>
          <span className="px-2 py-0.5 bg-gray-100 rounded">JPG</span>
          <span className="px-2 py-0.5 bg-gray-100 rounded">PNG</span>
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// FILE LIST
// =============================================================================

function FileItem({
  file,
  onTypeChange,
  onRemove,
}: {
  file: UploadedFile
  onTypeChange: (id: string, type: ImportedDocumentType) => void
  onRemove: (id: string) => void
}) {
  return (
    <div className="flex items-center gap-4 p-4 bg-white rounded-xl border border-gray-200">
      {/* File Icon */}
      <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0">
        <svg className="w-6 h-6 text-gray-500" 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>

      {/* File Info */}
      <div className="flex-1 min-w-0">
        <p className="font-medium text-gray-900 truncate">{file.file.name}</p>
        <p className="text-sm text-gray-500">{(file.file.size / 1024 / 1024).toFixed(2)} MB</p>
      </div>

      {/* Type Selector */}
      <select
        value={file.type}
        onChange={e => onTypeChange(file.id, e.target.value as ImportedDocumentType)}
        disabled={file.status !== 'pending'}
        className="px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500 disabled:opacity-50"
      >
        {DOCUMENT_TYPES.map(dt => (
          <option key={dt.value} value={dt.value}>
            {dt.icon} {dt.label}
          </option>
        ))}
      </select>

      {/* Status / Actions */}
      {file.status === 'pending' && (
        <button
          onClick={() => onRemove(file.id)}
          className="p-2 text-gray-400 hover:text-red-500 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="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      )}
      {file.status === 'uploading' && (
        <div className="flex items-center gap-2">
          <div className="w-20 h-2 bg-gray-200 rounded-full overflow-hidden">
            <div
              className="h-full bg-purple-600 rounded-full transition-all"
              style={{ width: `${file.progress}%` }}
            />
          </div>
          <span className="text-sm text-gray-500">{file.progress}%</span>
        </div>
      )}
      {file.status === 'analyzing' && (
        <div className="flex items-center gap-2 text-purple-600">
          <svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
          </svg>
          <span className="text-sm">Analysiere...</span>
        </div>
      )}
      {file.status === 'complete' && (
        <div className="flex items-center gap-1 text-green-600">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
          </svg>
          <span className="text-sm">Fertig</span>
        </div>
      )}
      {file.status === 'error' && (
        <div className="flex items-center gap-1 text-red-600">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
          <span className="text-sm">{file.error || 'Fehler'}</span>
        </div>
      )}
    </div>
  )
}

// =============================================================================
// GAP ANALYSIS PREVIEW
// =============================================================================

function GapAnalysisPreview({ analysis }: { analysis: GapAnalysis }) {
  return (
    <div className="bg-white rounded-xl border border-gray-200 p-6">
      <div className="flex items-center gap-3 mb-6">
        <div className="w-12 h-12 bg-orange-100 rounded-xl flex items-center justify-center">
          <span className="text-2xl">📊</span>
        </div>
        <div>
          <h3 className="text-lg font-semibold text-gray-900">Gap-Analyse Ergebnis</h3>
          <p className="text-sm text-gray-500">
            {analysis.totalGaps} Luecken in {analysis.gaps.length} Kategorien gefunden
          </p>
        </div>
      </div>

      {/* Summary Stats */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        <div className="text-center p-4 bg-red-50 rounded-xl">
          <div className="text-3xl font-bold text-red-600">{analysis.criticalGaps}</div>
          <div className="text-sm text-red-600 font-medium">Kritisch</div>
        </div>
        <div className="text-center p-4 bg-orange-50 rounded-xl">
          <div className="text-3xl font-bold text-orange-600">{analysis.highGaps}</div>
          <div className="text-sm text-orange-600 font-medium">Hoch</div>
        </div>
        <div className="text-center p-4 bg-yellow-50 rounded-xl">
          <div className="text-3xl font-bold text-yellow-600">{analysis.mediumGaps}</div>
          <div className="text-sm text-yellow-600 font-medium">Mittel</div>
        </div>
        <div className="text-center p-4 bg-green-50 rounded-xl">
          <div className="text-3xl font-bold text-green-600">{analysis.lowGaps}</div>
          <div className="text-sm text-green-600 font-medium">Niedrig</div>
        </div>
      </div>

      {/* Gap List */}
      <div className="space-y-3">
        {analysis.gaps.slice(0, 5).map((gap: GapItem) => (
          <div
            key={gap.id}
            className={`p-4 rounded-lg border-l-4 ${
              gap.severity === 'CRITICAL'
                ? 'bg-red-50 border-red-500'
                : gap.severity === 'HIGH'
                ? 'bg-orange-50 border-orange-500'
                : gap.severity === 'MEDIUM'
                ? 'bg-yellow-50 border-yellow-500'
                : 'bg-green-50 border-green-500'
            }`}
          >
            <div className="flex items-start justify-between">
              <div>
                <div className="font-medium text-gray-900">{gap.category}</div>
                <p className="text-sm text-gray-600 mt-1">{gap.description}</p>
              </div>
              <span
                className={`px-2 py-1 text-xs font-medium rounded ${
                  gap.severity === 'CRITICAL'
                    ? 'bg-red-100 text-red-700'
                    : gap.severity === 'HIGH'
                    ? 'bg-orange-100 text-orange-700'
                    : gap.severity === 'MEDIUM'
                    ? 'bg-yellow-100 text-yellow-700'
                    : 'bg-green-100 text-green-700'
                }`}
              >
                {gap.severity}
              </span>
            </div>
            <div className="mt-2 text-xs text-gray-500">
              Regulierung: {gap.regulation} | Aktion: {gap.requiredAction}
            </div>
          </div>
        ))}
        {analysis.gaps.length > 5 && (
          <p className="text-sm text-gray-500 text-center py-2">
            + {analysis.gaps.length - 5} weitere Luecken
          </p>
        )}
      </div>
    </div>
  )
}

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

export default function ImportPage() {
  const router = useRouter()
  const { state, addImportedDocument, setGapAnalysis, dispatch } = useSDK()
  const [files, setFiles] = useState<UploadedFile[]>([])
  const [isAnalyzing, setIsAnalyzing] = useState(false)
  const [analysisResult, setAnalysisResult] = useState<GapAnalysis | null>(null)

  const handleFilesAdded = useCallback((newFiles: File[]) => {
    const uploadedFiles: UploadedFile[] = newFiles.map(file => ({
      id: `file-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
      file,
      type: 'OTHER' as ImportedDocumentType,
      status: 'pending' as const,
      progress: 0,
    }))
    setFiles(prev => [...prev, ...uploadedFiles])
  }, [])

  const handleTypeChange = useCallback((id: string, type: ImportedDocumentType) => {
    setFiles(prev => prev.map(f => (f.id === id ? { ...f, type } : f)))
  }, [])

  const handleRemove = useCallback((id: string) => {
    setFiles(prev => prev.filter(f => f.id !== id))
  }, [])

  const handleAnalyze = async () => {
    if (files.length === 0) return

    setIsAnalyzing(true)
    const allGaps: GapItem[] = []

    for (let i = 0; i < files.length; i++) {
      const file = files[i]

      // Update to uploading
      setFiles(prev => prev.map(f => (f.id === file.id ? { ...f, status: 'uploading' as const } : f)))

      // Upload progress
      setFiles(prev => prev.map(f => (f.id === file.id ? { ...f, progress: 30 } : f)))

      // Prepare form data for backend
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('document_type', file.type)
      formData.append('tenant_id', 'default')

      setFiles(prev => prev.map(f => (f.id === file.id ? { ...f, progress: 60, status: 'analyzing' as const } : f)))

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

        if (response.ok) {
          const result = await response.json()

          // Create imported document from backend response
          const doc: ImportedDocument = {
            id: result.document_id || file.id,
            name: file.file.name,
            type: result.detected_type || file.type,
            fileUrl: URL.createObjectURL(file.file),
            uploadedAt: new Date(),
            analyzedAt: new Date(),
            analysisResult: {
              detectedType: result.detected_type || file.type,
              confidence: result.confidence || 0.85,
              extractedEntities: result.extracted_entities || [],
              gaps: result.gap_analysis?.gaps || [],
              recommendations: result.recommendations || [],
            },
          }

          addImportedDocument(doc)

          // Collect gaps
          if (result.gap_analysis?.gaps) {
            for (const gap of result.gap_analysis.gaps) {
              allGaps.push({
                id: gap.id,
                category: gap.category,
                description: gap.description,
                severity: gap.severity,
                regulation: gap.regulation,
                requiredAction: gap.required_action,
                relatedStepId: gap.related_step_id || '',
              })
            }
          }

          setFiles(prev => prev.map(f => (f.id === file.id ? { ...f, progress: 100, status: 'complete' as const } : f)))
        } else {
          setFiles(prev => prev.map(f => (f.id === file.id ? { ...f, status: 'error' as const, error: 'Analyse fehlgeschlagen' } : f)))
        }
      } catch {
        // Offline-Modus: create basic document without backend analysis
        const doc: ImportedDocument = {
          id: file.id,
          name: file.file.name,
          type: file.type,
          fileUrl: URL.createObjectURL(file.file),
          uploadedAt: new Date(),
          analyzedAt: new Date(),
          analysisResult: {
            detectedType: file.type,
            confidence: 0.5,
            extractedEntities: [],
            gaps: [],
            recommendations: ['Offline-Modus — Backend nicht erreichbar, manuelle Pruefung empfohlen'],
          },
        }
        addImportedDocument(doc)
        setFiles(prev => prev.map(f => (f.id === file.id ? { ...f, progress: 100, status: 'complete' as const } : f)))
      }
    }

    // Build gap analysis summary
    const gapAnalysis: GapAnalysis = {
      id: `analysis-${Date.now()}`,
      createdAt: new Date(),
      totalGaps: allGaps.length,
      criticalGaps: allGaps.filter(g => g.severity === 'CRITICAL').length,
      highGaps: allGaps.filter(g => g.severity === 'HIGH').length,
      mediumGaps: allGaps.filter(g => g.severity === 'MEDIUM').length,
      lowGaps: allGaps.filter(g => g.severity === 'LOW').length,
      gaps: allGaps,
      recommendedPackages: allGaps.length > 0 ? ['analyse', 'dokumentation'] : [],
    }

    setAnalysisResult(gapAnalysis)
    setGapAnalysis(gapAnalysis)
    setIsAnalyzing(false)

    // Mark step as complete
    dispatch({ type: 'COMPLETE_STEP', payload: 'import' })
  }

  const handleContinue = () => {
    router.push('/sdk/screening')
  }

  // Redirect if not existing customer
  if (state.customerType === 'new') {
    router.push('/sdk')
    return null
  }

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Dokumente importieren</h1>
        <p className="mt-1 text-gray-500">
          Laden Sie Ihre bestehenden Compliance-Dokumente hoch. Unsere KI analysiert sie und identifiziert Luecken fuer KI-Compliance.
        </p>
      </div>

      {/* Upload Zone */}
      <UploadZone onFilesAdded={handleFilesAdded} isDisabled={isAnalyzing} />

      {/* File List */}
      {files.length > 0 && (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="font-semibold text-gray-900">{files.length} Dokument(e)</h2>
            {!isAnalyzing && !analysisResult && (
              <button
                onClick={() => setFiles([])}
                className="text-sm text-gray-500 hover:text-red-500"
              >
                Alle entfernen
              </button>
            )}
          </div>
          <div className="space-y-3">
            {files.map(file => (
              <FileItem
                key={file.id}
                file={file}
                onTypeChange={handleTypeChange}
                onRemove={handleRemove}
              />
            ))}
          </div>
        </div>
      )}

      {/* Analyze Button */}
      {files.length > 0 && !analysisResult && (
        <div className="flex justify-center">
          <button
            onClick={handleAnalyze}
            disabled={isAnalyzing}
            className="px-8 py-3 bg-gradient-to-r from-purple-600 to-indigo-600 text-white font-medium rounded-xl hover:from-purple-700 hover:to-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center gap-2"
          >
            {isAnalyzing ? (
              <>
                <svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                </svg>
                Analysiere Dokumente...
              </>
            ) : (
              <>
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                </svg>
                Gap-Analyse starten
              </>
            )}
          </button>
        </div>
      )}

      {/* Analysis Result */}
      {analysisResult && <GapAnalysisPreview analysis={analysisResult} />}

      {/* Continue Button */}
      {analysisResult && (
        <div className="flex justify-between items-center pt-4 border-t border-gray-200">
          <p className="text-sm text-gray-500">
            Die Gap-Analyse wurde gespeichert. Sie koennen jetzt mit dem Compliance-Assessment fortfahren.
          </p>
          <button
            onClick={handleContinue}
            className="px-6 py-2.5 bg-green-600 text-white font-medium rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2"
          >
            Weiter zum Screening
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
            </svg>
          </button>
        </div>
      )}
    </div>
  )
}
