'use client'

import { useState, useEffect, useCallback } from 'react'
import { useTheme } from '@/lib/ThemeContext'
import { useLanguage } from '@/lib/LanguageContext'
import { useWorksheet } from '@/lib/worksheet-editor/WorksheetContext'

interface Session {
  id: string
  name: string
  description?: string
  vocabulary_count: number
  page_count: number
  status: string
  created_at?: string
}

interface DocumentImporterProps {
  isOpen: boolean
  onClose: () => void
}

export function DocumentImporter({ isOpen, onClose }: DocumentImporterProps) {
  const { isDark } = useTheme()
  const { t } = useLanguage()
  const { canvas, saveToHistory } = useWorksheet()

  const [sessions, setSessions] = useState<Session[]>([])
  const [selectedSession, setSelectedSession] = useState<Session | null>(null)
  const [selectedPage, setSelectedPage] = useState(1)
  const [isLoading, setIsLoading] = useState(false)
  const [isImporting, setIsImporting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [includeImages, setIncludeImages] = useState(true)

  // Load available sessions
  const loadSessions = useCallback(async () => {
    setIsLoading(true)
    setError(null)

    try {
      const { hostname, protocol } = window.location
      const apiBase = hostname === 'localhost' ? 'http://localhost:8086' : `${protocol}//${hostname}:8086`
      const response = await fetch(`${apiBase}/api/v1/worksheet/sessions/available`)

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
      }

      const data = await response.json()
      setSessions(data.sessions || [])
    } catch (err) {
      console.error('Failed to load sessions:', err)
      setError('Konnte Sessions nicht laden. Ist der Server erreichbar?')
    } finally {
      setIsLoading(false)
    }
  }, [])

  useEffect(() => {
    if (isOpen) {
      loadSessions()
    }
  }, [isOpen, loadSessions])

  // Handle import
  const handleImport = async () => {
    if (!selectedSession || !canvas) return

    setIsImporting(true)
    setError(null)

    try {
      const { hostname, protocol } = window.location
      const apiBase = hostname === 'localhost' ? 'http://localhost:8086' : `${protocol}//${hostname}:8086`
      const response = await fetch(`${apiBase}/api/v1/worksheet/reconstruct-from-session`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_id: selectedSession.id,
          page_number: selectedPage,
          include_images: includeImages,
          regenerate_graphics: false
        })
      })

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

      const result = await response.json()

      // Load canvas JSON
      if (result.canvas_json) {
        const canvasData = JSON.parse(result.canvas_json)

        // Clear current canvas and load new content
        canvas.clear()
        canvas.loadFromJSON(canvasData, () => {
          canvas.renderAll()
          saveToHistory(`Imported: ${selectedSession.name} Page ${selectedPage}`)
        })

        // Close modal
        onClose()
      }
    } catch (err) {
      console.error('Import failed:', err)
      setError(err instanceof Error ? err.message : 'Import fehlgeschlagen')
    } finally {
      setIsImporting(false)
    }
  }

  if (!isOpen) return null

  // Glassmorphism styles
  const overlayStyle = 'fixed inset-0 bg-black/50 backdrop-blur-sm z-50'
  const modalStyle = isDark
    ? 'backdrop-blur-xl bg-white/10 border border-white/20'
    : 'backdrop-blur-xl bg-white/90 border border-black/10 shadow-2xl'

  const cardStyle = (selected: boolean) => isDark
    ? selected
      ? 'bg-purple-500/30 border-purple-400/50'
      : 'bg-white/5 border-white/10 hover:bg-white/10'
    : selected
      ? 'bg-purple-100 border-purple-300'
      : 'bg-white/50 border-slate-200 hover:bg-slate-50'

  const labelStyle = isDark ? 'text-white/70' : 'text-slate-600'

  return (
    <div className={overlayStyle} onClick={onClose}>
      <div
        className={`fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-2xl max-h-[80vh] rounded-3xl p-6 overflow-hidden flex flex-col ${modalStyle}`}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${
              isDark ? 'bg-blue-500/20' : 'bg-blue-100'
            }`}>
              <svg className={`w-7 h-7 ${isDark ? 'text-blue-300' : 'text-blue-600'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} 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>
            <div>
              <h2 className={`text-xl font-semibold ${isDark ? 'text-white' : 'text-slate-900'}`}>
                Dokument importieren
              </h2>
              <p className={`text-sm ${labelStyle}`}>
                Rekonstruiere ein Arbeitsblatt aus einer Vokabel-Session
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className={`p-2 rounded-xl transition-colors ${
              isDark ? 'hover:bg-white/10 text-white/70' : 'hover:bg-slate-100 text-slate-500'
            }`}
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto">
          {/* Loading State */}
          {isLoading && (
            <div className="flex items-center justify-center py-12">
              <div className="w-8 h-8 border-4 border-purple-400 border-t-transparent rounded-full animate-spin" />
            </div>
          )}

          {/* Error State */}
          {error && (
            <div className={`p-4 rounded-xl mb-4 ${
              isDark ? 'bg-red-500/20 text-red-300' : 'bg-red-50 text-red-700'
            }`}>
              {error}
            </div>
          )}

          {/* No Sessions */}
          {!isLoading && sessions.length === 0 && (
            <div className={`text-center py-12 ${labelStyle}`}>
              <svg className="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} 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>
              <p className="text-lg font-medium mb-2">Keine Sessions gefunden</p>
              <p className="text-sm opacity-70">
                Verarbeite zuerst ein Dokument im Vokabel-Arbeitsblatt Generator
              </p>
            </div>
          )}

          {/* Session List */}
          {!isLoading && sessions.length > 0 && (
            <div className="space-y-3">
              <label className={`block text-sm font-medium mb-2 ${labelStyle}`}>
                Wähle eine Session:
              </label>

              {sessions.map((session) => (
                <button
                  key={session.id}
                  onClick={() => {
                    setSelectedSession(session)
                    setSelectedPage(1)
                  }}
                  className={`w-full p-4 rounded-xl border text-left transition-all ${cardStyle(selectedSession?.id === session.id)}`}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <h3 className={`font-medium ${isDark ? 'text-white' : 'text-slate-900'}`}>
                        {session.name}
                      </h3>
                      {session.description && (
                        <p className={`text-sm mt-1 ${labelStyle}`}>
                          {session.description}
                        </p>
                      )}
                      <div className={`flex items-center gap-4 mt-2 text-xs ${labelStyle}`}>
                        <span className="flex items-center gap-1">
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                          </svg>
                          {session.vocabulary_count} Vokabeln
                        </span>
                        <span className="flex items-center gap-1">
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                          </svg>
                          {session.page_count} Seiten
                        </span>
                        <span className={`px-2 py-0.5 rounded-full ${
                          session.status === 'completed'
                            ? isDark ? 'bg-green-500/20 text-green-300' : 'bg-green-100 text-green-700'
                            : isDark ? 'bg-yellow-500/20 text-yellow-300' : 'bg-yellow-100 text-yellow-700'
                        }`}>
                          {session.status}
                        </span>
                      </div>
                    </div>
                    {selectedSession?.id === session.id && (
                      <div className={`w-6 h-6 rounded-full flex items-center justify-center ${
                        isDark ? 'bg-purple-500' : 'bg-purple-600'
                      }`}>
                        <svg className="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                      </div>
                    )}
                  </div>
                </button>
              ))}
            </div>
          )}

          {/* Page Selection */}
          {selectedSession && selectedSession.page_count > 1 && (
            <div className="mt-6">
              <label className={`block text-sm font-medium mb-2 ${labelStyle}`}>
                Welche Seite importieren?
              </label>
              <div className="flex items-center gap-2 flex-wrap">
                {Array.from({ length: selectedSession.page_count }, (_, i) => i + 1).map((page) => (
                  <button
                    key={page}
                    onClick={() => setSelectedPage(page)}
                    className={`w-10 h-10 rounded-lg font-medium transition-all ${
                      selectedPage === page
                        ? isDark
                          ? 'bg-purple-500 text-white'
                          : 'bg-purple-600 text-white'
                        : isDark
                          ? 'bg-white/10 text-white/70 hover:bg-white/20'
                          : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                    }`}
                  >
                    {page}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Options */}
          {selectedSession && (
            <div className="mt-6 space-y-3">
              <label className={`block text-sm font-medium mb-2 ${labelStyle}`}>
                Optionen:
              </label>

              <label className={`flex items-center gap-3 p-3 rounded-xl border cursor-pointer transition-all ${
                isDark
                  ? 'bg-white/5 border-white/10 hover:bg-white/10'
                  : 'bg-white/50 border-slate-200 hover:bg-slate-50'
              }`}>
                <input
                  type="checkbox"
                  checked={includeImages}
                  onChange={(e) => setIncludeImages(e.target.checked)}
                  className="w-5 h-5 rounded"
                />
                <div>
                  <span className={`font-medium ${isDark ? 'text-white' : 'text-slate-900'}`}>
                    Bilder extrahieren
                  </span>
                  <p className={`text-sm ${labelStyle}`}>
                    Versuche Grafiken aus dem Original-PDF zu übernehmen
                  </p>
                </div>
              </label>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="mt-6 flex items-center justify-end gap-3">
          <button
            onClick={onClose}
            className={`px-5 py-2.5 rounded-xl font-medium transition-colors ${
              isDark
                ? 'bg-white/10 text-white hover:bg-white/20'
                : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
            }`}
          >
            Abbrechen
          </button>
          <button
            onClick={handleImport}
            disabled={!selectedSession || isImporting}
            className={`px-5 py-2.5 rounded-xl font-medium transition-all flex items-center gap-2 ${
              isDark
                ? 'bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:shadow-lg hover:shadow-purple-500/30'
                : 'bg-gradient-to-r from-purple-600 to-pink-600 text-white hover:shadow-lg hover:shadow-purple-600/30'
            } disabled:opacity-50 disabled:cursor-not-allowed`}
          >
            {isImporting ? (
              <>
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                Rekonstruiere...
              </>
            ) : (
              <>
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                </svg>
                Importieren
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  )
}
