/**
 * BYOEH Upload Wizard Component
 *
 * 5-step wizard for uploading Erwartungshorizonte with client-side encryption.
 * Step content extracted to eh-wizard/EHWizardSteps.tsx.
 */

import { useState, useEffect, useCallback } from 'react'
import { encryptFile, generateSalt, isEncryptionSupported } from '../services/encryption'
import { ehApi } from '../services/api'
import { FileStep, MetadataStep, RightsStep, EncryptionStep, SummaryStep } from './eh-wizard/EHWizardSteps'
import type { EHMetadata } from './eh-wizard/EHWizardSteps'

interface EHUploadWizardProps {
  onClose: () => void
  onComplete?: (ehId: string) => void
  onSuccess?: (ehId: string) => void
  klausurSubject?: string
  klausurYear?: number
  defaultSubject?: string
  defaultYear?: number
  klausurId?: string
}

type WizardStep = 'file' | 'metadata' | 'rights' | 'encryption' | 'summary'
const WIZARD_STEPS: WizardStep[] = ['file', 'metadata', 'rights', 'encryption', 'summary']
const STEP_LABELS: Record<WizardStep, string> = { file: 'Datei', metadata: 'Metadaten', rights: 'Rechte', encryption: 'Verschluesselung', summary: 'Zusammenfassung' }

function EHUploadWizard({ onClose, onComplete, onSuccess, klausurSubject, klausurYear, defaultSubject, defaultYear, klausurId }: EHUploadWizardProps) {
  const effectiveSubject = klausurSubject || defaultSubject || 'deutsch'
  const effectiveYear = klausurYear || defaultYear || new Date().getFullYear()
  const handleComplete = onComplete || onSuccess || (() => {})

  const [currentStep, setCurrentStep] = useState<WizardStep>('file')
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [fileError, setFileError] = useState<string | null>(null)
  const [metadata, setMetadata] = useState<EHMetadata>({ title: '', subject: effectiveSubject, niveau: 'eA', year: effectiveYear, aufgaben_nummer: '' })
  const [rightsConfirmed, setRightsConfirmed] = useState(false)
  const [passphrase, setPassphrase] = useState('')
  const [passphraseConfirm, setPassphraseConfirm] = useState('')
  const [showPassphrase, setShowPassphrase] = useState(false)
  const [passphraseStrength, setPassphraseStrength] = useState<'weak' | 'medium' | 'strong'>('weak')
  const [uploading, setUploading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [uploadError, setUploadError] = useState<string | null>(null)
  const encryptionSupported = isEncryptionSupported()

  useEffect(() => {
    if (passphrase.length < 8) setPassphraseStrength('weak')
    else if (passphrase.length < 12 || !/\d/.test(passphrase) || !/[A-Z]/.test(passphrase)) setPassphraseStrength('medium')
    else setPassphraseStrength('strong')
  }, [passphrase])

  const currentStepIndex = WIZARD_STEPS.indexOf(currentStep)
  const isFirstStep = currentStepIndex === 0
  const isLastStep = currentStepIndex === WIZARD_STEPS.length - 1

  const goNext = useCallback(() => { if (!isLastStep) setCurrentStep(WIZARD_STEPS[currentStepIndex + 1]) }, [currentStepIndex, isLastStep])
  const goBack = useCallback(() => { if (!isFirstStep) setCurrentStep(WIZARD_STEPS[currentStepIndex - 1]) }, [currentStepIndex, isFirstStep])

  const isStepValid = useCallback((step: WizardStep): boolean => {
    switch (step) {
      case 'file': return selectedFile !== null && fileError === null
      case 'metadata': return metadata.title.trim().length > 0 && metadata.subject.length > 0
      case 'rights': return rightsConfirmed
      case 'encryption': return passphrase.length >= 8 && passphrase === passphraseConfirm
      case 'summary': return true
      default: return false
    }
  }, [selectedFile, fileError, metadata, rightsConfirmed, passphrase, passphraseConfirm])

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      if (file.type !== 'application/pdf') { setFileError('Nur PDF-Dateien sind erlaubt'); setSelectedFile(null); return }
      if (file.size > 50 * 1024 * 1024) { setFileError('Datei ist zu gross (max. 50MB)'); setSelectedFile(null); return }
      setFileError(null); setSelectedFile(file)
      if (!metadata.title) { const name = file.name.replace(/\.pdf$/i, '').replace(/[_-]/g, ' '); setMetadata(prev => ({ ...prev, title: name })) }
    }
  }

  const handleUpload = async () => {
    if (!selectedFile || !encryptionSupported) return
    setUploading(true); setUploadProgress(10); setUploadError(null)
    try {
      generateSalt(); setUploadProgress(20)
      const encrypted = await encryptFile(selectedFile, passphrase); setUploadProgress(50)
      const formData = new FormData()
      formData.append('file', new Blob([encrypted.encryptedData], { type: 'application/octet-stream' }), 'encrypted.bin')
      formData.append('metadata_json', JSON.stringify({
        metadata: { title: metadata.title, subject: metadata.subject, niveau: metadata.niveau, year: metadata.year, aufgaben_nummer: metadata.aufgaben_nummer || null },
        encryption_key_hash: encrypted.keyHash, salt: encrypted.salt, rights_confirmed: true, original_filename: selectedFile.name
      }))
      setUploadProgress(70)
      const response = await ehApi.uploadEH(formData); setUploadProgress(90)
      if (klausurId && response.id) { try { await ehApi.linkToKlausur(response.id, klausurId) } catch (linkError) { console.warn('Failed to auto-link EH:', linkError) } }
      setUploadProgress(100); handleComplete(response.id)
    } catch (error) { console.error('Upload failed:', error); setUploadError(error instanceof Error ? error.message : 'Upload fehlgeschlagen') }
    finally { setUploading(false) }
  }

  const renderStepContent = () => {
    switch (currentStep) {
      case 'file': return <FileStep selectedFile={selectedFile} fileError={fileError} encryptionSupported={encryptionSupported} onFileSelect={handleFileSelect} />
      case 'metadata': return <MetadataStep metadata={metadata} onMetadataChange={setMetadata} />
      case 'rights': return <RightsStep rightsConfirmed={rightsConfirmed} onRightsConfirmedChange={setRightsConfirmed} />
      case 'encryption': return <EncryptionStep passphrase={passphrase} passphraseConfirm={passphraseConfirm} showPassphrase={showPassphrase} passphraseStrength={passphraseStrength} onPassphraseChange={setPassphrase} onPassphraseConfirmChange={setPassphraseConfirm} onToggleShow={() => setShowPassphrase(!showPassphrase)} />
      case 'summary': return <SummaryStep selectedFile={selectedFile} metadata={metadata} uploading={uploading} uploadProgress={uploadProgress} uploadError={uploadError} />
      default: return null
    }
  }

  return (
    <div className="eh-wizard-overlay">
      <div className="eh-wizard-modal">
        <div className="eh-wizard-header">
          <h2>Erwartungshorizont hochladen</h2>
          <button className="eh-wizard-close" onClick={onClose}>&times;</button>
        </div>
        <div className="eh-wizard-progress">
          {WIZARD_STEPS.map((step, index) => (
            <div key={step} className={`eh-progress-step ${index < currentStepIndex ? 'completed' : index === currentStepIndex ? 'active' : ''}`}>
              <div className="eh-progress-dot">{index < currentStepIndex ? '\u2713' : index + 1}</div>
              <span className="eh-progress-label">{STEP_LABELS[step]}</span>
            </div>
          ))}
        </div>
        <div className="eh-wizard-content">{renderStepContent()}</div>
        <div className="eh-wizard-footer">
          <button className="eh-btn eh-btn-secondary" onClick={isFirstStep ? onClose : goBack} disabled={uploading}>{isFirstStep ? 'Abbrechen' : 'Zurueck'}</button>
          {isLastStep ? (
            <button className="eh-btn eh-btn-primary" onClick={handleUpload} disabled={uploading || !isStepValid(currentStep)}>{uploading ? 'Wird hochgeladen...' : 'Hochladen'}</button>
          ) : (
            <button className="eh-btn eh-btn-primary" onClick={goNext} disabled={!isStepValid(currentStep)}>Weiter</button>
          )}
        </div>
      </div>
    </div>
  )
}

export default EHUploadWizard
