'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useTheme } from '@/lib/ThemeContext'
import { useLanguage } from '@/lib/LanguageContext'
import { useAlerts, Alert, getImportanceColor, getRelativeTime } from '@/lib/AlertsContext'
import { Sidebar } from '@/components/Sidebar'
import { AlertsWizard } from '@/components/AlertsWizard'
import { InfoBox, TipBox } from '@/components/InfoBox'
import { Footer } from '@/components/Footer'
import { LanguageDropdown } from '@/components/LanguageDropdown'
import { ThemeToggle } from '@/components/ThemeToggle'

// Alert Detail Modal
function AlertDetailModal({
  alert,
  onClose,
  onMarkRead
}: {
  alert: Alert
  onClose: () => void
  onMarkRead: () => void
}) {
  const { isDark } = useTheme()

  useEffect(() => {
    if (!alert.isRead) {
      onMarkRead()
    }
  }, [alert, onMarkRead])

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} />
      <div className={`relative w-full max-w-2xl rounded-3xl border p-8 max-h-[90vh] overflow-y-auto ${
        isDark
          ? 'bg-slate-900 border-white/20'
          : 'bg-white border-slate-200 shadow-2xl'
      }`}>
        {/* Header */}
        <div className="flex items-start justify-between mb-4">
          <div className="flex items-center gap-3">
            <span className={`px-3 py-1 rounded-full text-xs font-medium border ${getImportanceColor(alert.importance, isDark)}`}>
              {alert.importance}
            </span>
            <span className={`text-xs ${isDark ? 'text-white/60' : 'text-slate-500'}`}>
              {getRelativeTime(alert.timestamp)}
            </span>
          </div>
          <button
            onClick={onClose}
            className={`p-2 rounded-lg ${isDark ? 'hover:bg-white/10' : 'hover:bg-slate-100'}`}
          >
            <svg className={`w-5 h-5 ${isDark ? 'text-white/60' : 'text-slate-400'}`} 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>

        {/* Title */}
        <h2 className={`text-xl font-bold mb-4 ${isDark ? 'text-white' : 'text-slate-900'}`}>
          {alert.title}
        </h2>

        {/* LLM Summary */}
        <div className={`rounded-xl p-4 mb-6 ${isDark ? 'bg-white/5' : 'bg-slate-50'}`}>
          <h4 className={`text-sm font-medium mb-2 flex items-center gap-2 ${isDark ? 'text-white/80' : 'text-slate-700'}`}>
            <span>🤖</span> KI-Zusammenfassung
          </h4>
          <p className={isDark ? 'text-white/80' : 'text-slate-600'}>
            {alert.summary}
          </p>
        </div>

        {/* Sources */}
        <div className="space-y-3">
          <h4 className={`text-sm font-medium ${isDark ? 'text-white/80' : 'text-slate-700'}`}>
            Quellen:
          </h4>
          {alert.sources.map((source, idx) => (
            <a
              key={idx}
              href={source.url}
              target="_blank"
              rel="noopener noreferrer"
              className={`block p-3 rounded-lg transition-all ${
                isDark
                  ? 'bg-white/5 hover:bg-white/10'
                  : 'bg-slate-50 hover:bg-slate-100'
              }`}
            >
              <p className={`text-sm font-medium ${isDark ? 'text-blue-400' : 'text-blue-600'}`}>
                {source.title}
              </p>
              <p className={`text-xs ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
                {source.domain}
              </p>
            </a>
          ))}
        </div>

        {/* Original Source */}
        <div className={`mt-6 pt-4 border-t ${isDark ? 'border-white/10' : 'border-slate-200'}`}>
          <p className={`text-xs ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
            Quelle: {alert.source}
          </p>
        </div>
      </div>
    </div>
  )
}

// Alert Headline Component
function AlertHeadline({
  alert,
  onClick
}: {
  alert: Alert
  onClick: () => void
}) {
  const { isDark } = useTheme()

  return (
    <button
      onClick={onClick}
      className={`w-full text-left p-4 rounded-xl transition-all group ${
        isDark
          ? `bg-white/5 hover:bg-white/10 ${!alert.isRead ? 'border-l-4 border-amber-500' : ''}`
          : `bg-slate-50 hover:bg-slate-100 ${!alert.isRead ? 'border-l-4 border-amber-500' : ''}`
      }`}
    >
      <div className="flex items-start gap-3">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <span className={`px-2 py-0.5 rounded-full text-xs font-medium border ${getImportanceColor(alert.importance, isDark)}`}>
              {alert.importance}
            </span>
            <span className={`text-xs ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
              {getRelativeTime(alert.timestamp)}
            </span>
            {!alert.isRead && (
              <span className="w-2 h-2 rounded-full bg-amber-500" />
            )}
          </div>
          <h3 className={`font-medium truncate ${isDark ? 'text-white' : 'text-slate-900'}`}>
            {alert.title}
          </h3>
          <p className={`text-sm truncate ${isDark ? 'text-white/60' : 'text-slate-500'}`}>
            {alert.summary}
          </p>
        </div>
        <svg className={`w-5 h-5 flex-shrink-0 transition-colors ${
          isDark ? 'text-white/30 group-hover:text-white/60' : 'text-slate-300 group-hover:text-slate-600'
        }`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
        </svg>
      </div>
    </button>
  )
}

export default function AlertsPage() {
  const router = useRouter()
  const { isDark } = useTheme()
  const { t } = useLanguage()
  const {
    alerts,
    unreadCount,
    isLoading,
    topics,
    settings,
    markAsRead,
    markAllAsRead,
    updateSettings
  } = useAlerts()

  const [selectedAlert, setSelectedAlert] = useState<Alert | null>(null)
  const [showWizard, setShowWizard] = useState(false)
  const [filterImportance, setFilterImportance] = useState<string>('all')
  const [viewMode, setViewMode] = useState<'simple' | 'expert'>('simple')

  // Zeige Wizard wenn noch nicht abgeschlossen
  useEffect(() => {
    if (!settings.wizardCompleted && topics.length === 0) {
      setShowWizard(true)
    }
  }, [settings.wizardCompleted, topics.length])

  // Gefilterte Alerts
  const filteredAlerts = alerts.filter(alert => {
    if (filterImportance === 'all') return true
    if (filterImportance === 'unread') return !alert.isRead
    return alert.importance === filterImportance
  })

  // Wizard-Modus
  if (showWizard) {
    return (
      <AlertsWizard
        onComplete={() => setShowWizard(false)}
        onSkip={() => {
          updateSettings({ wizardCompleted: true })
          setShowWizard(false)
        }}
      />
    )
  }

  return (
    <div className={`min-h-screen relative overflow-hidden flex flex-col ${
      isDark
        ? 'bg-gradient-to-br from-indigo-900 via-purple-900 to-pink-800'
        : 'bg-gradient-to-br from-slate-100 via-blue-50 to-indigo-100'
    }`}>
      {/* Animated Background Blobs */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className={`absolute -top-40 -right-40 w-80 h-80 rounded-full mix-blend-multiply filter blur-3xl animate-blob ${
          isDark ? 'bg-amber-500 opacity-70' : 'bg-amber-300 opacity-50'
        }`} />
        <div className={`absolute -bottom-40 -left-40 w-80 h-80 rounded-full mix-blend-multiply filter blur-3xl animate-blob animation-delay-2000 ${
          isDark ? 'bg-orange-500 opacity-70' : 'bg-orange-300 opacity-50'
        }`} />
      </div>

      <div className="relative z-10 flex min-h-screen gap-6 p-4">
        {/* Sidebar */}
        <Sidebar selectedTab="alerts" />

        {/* Main Content */}
        <main className="flex-1">
          {/* Header */}
          <div className="flex items-center justify-between mb-8">
            <div>
              <h1 className={`text-4xl font-bold mb-2 flex items-center gap-3 ${isDark ? 'text-white' : 'text-slate-900'}`}>
                <span>🔔</span> Alerts
                {unreadCount > 0 && (
                  <span className="px-3 py-1 text-sm font-medium rounded-full bg-amber-500/20 text-amber-400 border border-amber-500/30">
                    {unreadCount} neu
                  </span>
                )}
              </h1>
              <p className={isDark ? 'text-white/60' : 'text-slate-600'}>
                Aktuelle Nachrichten zu Ihren Bildungsthemen
              </p>
            </div>

            <div className="flex items-center gap-4">
              {/* Mode Toggle */}
              <div className={`flex rounded-xl overflow-hidden border ${isDark ? 'border-white/20' : 'border-slate-200'}`}>
                <button
                  onClick={() => setViewMode('simple')}
                  className={`px-4 py-2 text-sm font-medium transition-all ${
                    viewMode === 'simple'
                      ? 'bg-amber-500 text-white'
                      : isDark ? 'text-white/60 hover:text-white' : 'text-slate-500 hover:text-slate-900'
                  }`}
                >
                  Einfach
                </button>
                <button
                  onClick={() => setViewMode('expert')}
                  className={`px-4 py-2 text-sm font-medium transition-all ${
                    viewMode === 'expert'
                      ? 'bg-amber-500 text-white'
                      : isDark ? 'text-white/60 hover:text-white' : 'text-slate-500 hover:text-slate-900'
                  }`}
                >
                  Experte
                </button>
              </div>

              <LanguageDropdown />
              <ThemeToggle />

              <button
                onClick={() => setShowWizard(true)}
                className={`p-3 backdrop-blur-xl border rounded-2xl hover:bg-white/20 transition-all ${
                  isDark
                    ? 'bg-white/10 border-white/20 text-white'
                    : 'bg-black/5 border-black/10 text-slate-700'
                }`}
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
              </button>
            </div>
          </div>

          <div className="grid grid-cols-3 gap-6">
            {/* Alerts Liste */}
            <div className={`col-span-2 backdrop-blur-xl border rounded-3xl p-6 ${
              isDark
                ? 'bg-white/10 border-white/20'
                : 'bg-white/70 border-black/10 shadow-lg'
            }`}>
              {/* Filter Bar */}
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center gap-2">
                  {['all', 'unread', 'KRITISCH', 'DRINGEND', 'WICHTIG'].map((filter) => (
                    <button
                      key={filter}
                      onClick={() => setFilterImportance(filter)}
                      className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-all ${
                        filterImportance === filter
                          ? 'bg-amber-500/20 text-amber-400 border border-amber-500/30'
                          : isDark
                            ? 'text-white/60 hover:text-white hover:bg-white/10'
                            : 'text-slate-500 hover:text-slate-900 hover:bg-slate-100'
                      }`}
                    >
                      {filter === 'all' ? 'Alle' : filter === 'unread' ? 'Ungelesen' : filter}
                    </button>
                  ))}
                </div>
                {unreadCount > 0 && (
                  <button
                    onClick={markAllAsRead}
                    className={`text-sm ${isDark ? 'text-white/60 hover:text-white' : 'text-slate-500 hover:text-slate-900'}`}
                  >
                    Alle als gelesen markieren
                  </button>
                )}
              </div>

              {/* Alerts */}
              {isLoading ? (
                <div className="flex items-center justify-center py-12">
                  <div className="animate-spin rounded-full h-8 w-8 border-2 border-amber-500 border-t-transparent" />
                </div>
              ) : filteredAlerts.length === 0 ? (
                <div className={`text-center py-12 ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
                  <span className="text-4xl block mb-4">📭</span>
                  <p>Keine Alerts gefunden</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {filteredAlerts.map(alert => (
                    <AlertHeadline
                      key={alert.id}
                      alert={alert}
                      onClick={() => setSelectedAlert(alert)}
                    />
                  ))}
                </div>
              )}
            </div>

            {/* Right Sidebar */}
            <div className="space-y-6">
              {/* Topics */}
              <div className={`backdrop-blur-xl border rounded-3xl p-6 ${
                isDark
                  ? 'bg-white/10 border-white/20'
                  : 'bg-white/70 border-black/10 shadow-lg'
              }`}>
                <h2 className={`text-lg font-semibold mb-4 flex items-center gap-2 ${isDark ? 'text-white' : 'text-slate-900'}`}>
                  <span>📋</span> Meine Themen
                </h2>
                {topics.length === 0 ? (
                  <p className={`text-sm ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
                    Noch keine Themen konfiguriert.
                  </p>
                ) : (
                  <div className="space-y-2">
                    {topics.map(topic => (
                      <div
                        key={topic.id}
                        className={`flex items-center gap-3 p-3 rounded-lg ${
                          isDark ? 'bg-white/5' : 'bg-slate-50'
                        }`}
                      >
                        <span className="text-lg">{topic.icon}</span>
                        <div className="flex-1 min-w-0">
                          <p className={`font-medium text-sm ${isDark ? 'text-white' : 'text-slate-900'}`}>
                            {topic.name}
                          </p>
                          <p className={`text-xs truncate ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
                            {topic.keywords.slice(0, 3).join(', ')}
                          </p>
                        </div>
                        <div className={`w-2 h-2 rounded-full ${topic.isActive ? 'bg-green-500' : 'bg-slate-400'}`} />
                      </div>
                    ))}
                  </div>
                )}
                <button
                  onClick={() => setShowWizard(true)}
                  className={`w-full mt-4 p-3 rounded-xl text-sm font-medium transition-all ${
                    isDark
                      ? 'bg-white/10 text-white hover:bg-white/20'
                      : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
                  }`}
                >
                  + Thema hinzufuegen
                </button>
              </div>

              {/* Stats */}
              <div className={`backdrop-blur-xl border rounded-3xl p-6 ${
                isDark
                  ? 'bg-white/10 border-white/20'
                  : 'bg-white/70 border-black/10 shadow-lg'
              }`}>
                <h2 className={`text-lg font-semibold mb-4 flex items-center gap-2 ${isDark ? 'text-white' : 'text-slate-900'}`}>
                  <span>📊</span> Statistik
                </h2>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className={`text-sm ${isDark ? 'text-white/60' : 'text-slate-500'}`}>Gesamt</span>
                    <span className={`font-medium ${isDark ? 'text-white' : 'text-slate-900'}`}>{alerts.length}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className={`text-sm ${isDark ? 'text-white/60' : 'text-slate-500'}`}>Ungelesen</span>
                    <span className="font-medium text-amber-500">{unreadCount}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className={`text-sm ${isDark ? 'text-white/60' : 'text-slate-500'}`}>Themen</span>
                    <span className={`font-medium ${isDark ? 'text-white' : 'text-slate-900'}`}>{topics.length}</span>
                  </div>
                </div>
              </div>

              {/* Info */}
              <TipBox title="LLM-Zusammenfassungen" icon="🤖">
                <p className="text-sm">
                  Alle Alerts werden automatisch mit KI zusammengefasst,
                  um Ihnen Zeit zu sparen.
                </p>
              </TipBox>
            </div>
          </div>
        </main>
      </div>

      {/* Alert Detail Modal */}
      {selectedAlert && (
        <AlertDetailModal
          alert={selectedAlert}
          onClose={() => setSelectedAlert(null)}
          onMarkRead={() => markAsRead(selectedAlert.id)}
        />
      )}

      <Footer />

      {/* Blob Animation Styles */}
      <style jsx>{`
        @keyframes blob {
          0% { transform: translate(0px, 0px) scale(1); }
          33% { transform: translate(30px, -50px) scale(1.1); }
          66% { transform: translate(-20px, 20px) scale(0.9); }
          100% { transform: translate(0px, 0px) scale(1); }
        }
        .animate-blob {
          animation: blob 7s infinite;
        }
        .animation-delay-2000 {
          animation-delay: 2s;
        }
      `}</style>
    </div>
  )
}
