'use client'

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

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

export function ExportPanel({ isOpen, onClose }: ExportPanelProps) {
  const { isDark } = useTheme()
  const { t } = useLanguage()
  const { exportToPDF, exportToImage, document, saveDocument, isDirty } = useWorksheet()

  const [isExporting, setIsExporting] = useState(false)
  const [exportFormat, setExportFormat] = useState<'pdf' | 'png' | 'jpg'>('pdf')

  const handleExport = async () => {
    setIsExporting(true)

    try {
      let blob: Blob
      let filename: string

      if (exportFormat === 'pdf') {
        blob = await exportToPDF()
        filename = `${document?.title || 'Arbeitsblatt'}.pdf`
      } else {
        blob = await exportToImage(exportFormat)
        filename = `${document?.title || 'Arbeitsblatt'}.${exportFormat}`
      }

      // Download file
      const url = URL.createObjectURL(blob)
      const a = window.document.createElement('a')
      a.href = url
      a.download = filename
      window.document.body.appendChild(a)
      a.click()
      window.document.body.removeChild(a)
      URL.revokeObjectURL(url)

      onClose()
    } catch (error) {
      console.error('Export failed:', error)
      alert('Export fehlgeschlagen. Bitte versuchen Sie es erneut.')
    } finally {
      setIsExporting(false)
    }
  }

  const handleSave = async () => {
    setIsExporting(true)
    try {
      await saveDocument()
      alert('Dokument gespeichert!')
    } catch (error) {
      console.error('Save failed:', error)
      alert('Speichern fehlgeschlagen.')
    } finally {
      setIsExporting(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 buttonStyle = (active: boolean) => isDark
    ? active
      ? 'bg-purple-500/30 text-purple-300 border border-purple-400/50'
      : 'bg-white/5 text-white/70 border border-transparent hover:bg-white/10'
    : active
      ? 'bg-purple-100 text-purple-700 border border-purple-300'
      : 'bg-slate-50 text-slate-600 border border-transparent hover:bg-slate-100'

  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-md rounded-3xl p-6 ${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-10 h-10 rounded-xl flex items-center justify-center ${
              isDark ? 'bg-purple-500/20' : 'bg-purple-100'
            }`}>
              <svg className={`w-6 h-6 ${isDark ? 'text-purple-300' : 'text-purple-600'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
            </div>
            <div>
              <h2 className={`text-xl font-semibold ${isDark ? 'text-white' : 'text-slate-900'}`}>
                Exportieren
              </h2>
              <p className={`text-sm ${labelStyle}`}>
                Arbeitsblatt speichern oder exportieren
              </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>

        {/* Save Section */}
        <div className="mb-6">
          <button
            onClick={handleSave}
            disabled={isExporting}
            className={`w-full py-4 rounded-xl font-medium transition-all flex items-center justify-center gap-3 ${
              isDark
                ? 'bg-green-500/30 text-green-300 hover:bg-green-500/40'
                : 'bg-green-600 text-white hover:bg-green-700'
            } ${isExporting ? 'opacity-50 cursor-not-allowed' : ''}`}
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
            </svg>
            Speichern
            {isDirty && (
              <span className={`px-2 py-0.5 rounded-full text-xs ${
                isDark ? 'bg-yellow-500/30 text-yellow-300' : 'bg-yellow-100 text-yellow-700'
              }`}>
                Ungespeichert
              </span>
            )}
          </button>
        </div>

        {/* Export Format Selection */}
        <div className="mb-4">
          <label className={`block text-sm font-medium mb-3 ${labelStyle}`}>
            Export-Format
          </label>
          <div className="grid grid-cols-3 gap-3">
            <button
              onClick={() => setExportFormat('pdf')}
              className={`py-4 rounded-xl transition-all flex flex-col items-center gap-2 ${buttonStyle(exportFormat === 'pdf')}`}
            >
              <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} 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>
              <span className="text-sm font-medium">PDF</span>
            </button>

            <button
              onClick={() => setExportFormat('png')}
              className={`py-4 rounded-xl transition-all flex flex-col items-center gap-2 ${buttonStyle(exportFormat === 'png')}`}
            >
              <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
              <span className="text-sm font-medium">PNG</span>
            </button>

            <button
              onClick={() => setExportFormat('jpg')}
              className={`py-4 rounded-xl transition-all flex flex-col items-center gap-2 ${buttonStyle(exportFormat === 'jpg')}`}
            >
              <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
              <span className="text-sm font-medium">JPG</span>
            </button>
          </div>
        </div>

        {/* Export Button */}
        <button
          onClick={handleExport}
          disabled={isExporting}
          className={`w-full py-4 rounded-xl font-medium transition-all flex items-center justify-center gap-2 ${
            isDark
              ? 'bg-purple-500/30 text-purple-300 hover:bg-purple-500/40'
              : 'bg-purple-600 text-white hover:bg-purple-700'
          } ${isExporting ? 'opacity-50 cursor-not-allowed' : ''}`}
        >
          {isExporting ? (
            <>
              <svg className="animate-spin w-5 h-5" 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>
              Exportiere...
            </>
          ) : (
            <>
              <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-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
              Als {exportFormat.toUpperCase()} exportieren
            </>
          )}
        </button>
      </div>
    </div>
  )
}
