'use client'

import { useState, useEffect, useCallback, useRef } from 'react'
import { useTheme } from '@/lib/ThemeContext'
import { useMessages } from '@/lib/MessagesContext'
import { useRouter } from 'next/navigation'

interface ChatMessage {
  id: string
  senderName: string
  senderAvatar?: string
  senderInitials: string
  content: string
  timestamp: Date
  conversationId: string
  isGroup?: boolean
}

interface ChatOverlayProps {
  /** Auto-dismiss after X milliseconds (0 = manual dismiss only) */
  autoDismissMs?: number
  /** Maximum messages to queue */
  maxQueue?: number
  /** Enable typewriter effect */
  typewriterEnabled?: boolean
  /** Typewriter speed in ms per character */
  typewriterSpeed?: number
  /** Enable sound notification */
  soundEnabled?: boolean
}

export function ChatOverlay({
  autoDismissMs = 0,
  maxQueue = 5,
  typewriterEnabled = true,
  typewriterSpeed = 30,
  soundEnabled = false
}: ChatOverlayProps) {
  const { isDark } = useTheme()
  const router = useRouter()
  const { conversations, contacts, messages: allMessages } = useMessages()

  const [messageQueue, setMessageQueue] = useState<ChatMessage[]>([])
  const [currentMessage, setCurrentMessage] = useState<ChatMessage | null>(null)
  const [isVisible, setIsVisible] = useState(false)
  const [isExiting, setIsExiting] = useState(false)
  const [displayedText, setDisplayedText] = useState('')
  const [isTyping, setIsTyping] = useState(false)
  const [replyText, setReplyText] = useState('')
  const [isReplying, setIsReplying] = useState(false)

  const audioRef = useRef<HTMLAudioElement | null>(null)
  const typewriterRef = useRef<NodeJS.Timeout | null>(null)
  const dismissTimerRef = useRef<NodeJS.Timeout | null>(null)

  // Initialize audio
  useEffect(() => {
    if (soundEnabled && typeof window !== 'undefined') {
      audioRef.current = new Audio('/sounds/message-pop.mp3')
      audioRef.current.volume = 0.3
    }
  }, [soundEnabled])

  // Simulate incoming messages (for demo - replace with real WebSocket later)
  useEffect(() => {
    // Demo: Show a message after 5 seconds
    const demoTimer = setTimeout(() => {
      const demoMessage: ChatMessage = {
        id: `demo-${Date.now()}`,
        senderName: 'Familie Mueller',
        senderInitials: 'FM',
        content: 'Hallo! Lisa hatte heute leider Fieber und konnte nicht zur Schule kommen. Könnten Sie uns bitte die Hausaufgaben für morgen mitteilen?',
        timestamp: new Date(),
        conversationId: 'conv1',
        isGroup: false
      }
      addToQueue(demoMessage)
    }, 5000)

    return () => clearTimeout(demoTimer)
  }, [])

  // Add message to queue
  const addToQueue = useCallback((message: ChatMessage) => {
    setMessageQueue(prev => {
      if (prev.length >= maxQueue) {
        return [...prev.slice(1), message]
      }
      return [...prev, message]
    })
  }, [maxQueue])

  // Process queue - show next message
  useEffect(() => {
    if (!currentMessage && messageQueue.length > 0 && !isExiting) {
      const nextMessage = messageQueue[0]
      setMessageQueue(prev => prev.slice(1))
      setCurrentMessage(nextMessage)
      setIsVisible(true)
      setDisplayedText('')
      setIsTyping(true)

      // Play sound
      if (soundEnabled && audioRef.current) {
        audioRef.current.play().catch(() => {})
      }
    }
  }, [currentMessage, messageQueue, isExiting, soundEnabled])

  // Typewriter effect
  useEffect(() => {
    if (!currentMessage || !isTyping) return

    const fullText = currentMessage.content
    let charIndex = 0

    if (typewriterEnabled) {
      typewriterRef.current = setInterval(() => {
        charIndex++
        setDisplayedText(fullText.slice(0, charIndex))

        if (charIndex >= fullText.length) {
          if (typewriterRef.current) {
            clearInterval(typewriterRef.current)
          }
          setIsTyping(false)
        }
      }, typewriterSpeed)
    } else {
      setDisplayedText(fullText)
      setIsTyping(false)
    }

    return () => {
      if (typewriterRef.current) {
        clearInterval(typewriterRef.current)
      }
    }
  }, [currentMessage, isTyping, typewriterEnabled, typewriterSpeed])

  // Auto-dismiss timer
  useEffect(() => {
    if (currentMessage && autoDismissMs > 0 && !isTyping && !isReplying) {
      dismissTimerRef.current = setTimeout(() => {
        handleDismiss()
      }, autoDismissMs)
    }

    return () => {
      if (dismissTimerRef.current) {
        clearTimeout(dismissTimerRef.current)
      }
    }
  }, [currentMessage, autoDismissMs, isTyping, isReplying])

  // Dismiss current message
  const handleDismiss = useCallback(() => {
    setIsExiting(true)
    setTimeout(() => {
      setCurrentMessage(null)
      setIsVisible(false)
      setIsExiting(false)
      setDisplayedText('')
      setReplyText('')
      setIsReplying(false)
    }, 300) // Match exit animation duration
  }, [])

  // Open full conversation
  const handleOpenConversation = useCallback(() => {
    if (currentMessage) {
      router.push(`/messages?conversation=${currentMessage.conversationId}`)
      handleDismiss()
    }
  }, [currentMessage, router, handleDismiss])

  // Toggle reply mode
  const handleReplyClick = useCallback(() => {
    setIsReplying(true)
  }, [])

  // Send reply
  const handleSendReply = useCallback(() => {
    if (!replyText.trim() || !currentMessage) return

    // TODO: Actually send the message via MessagesContext
    console.log('Sending reply:', replyText, 'to conversation:', currentMessage.conversationId)

    // For now, just dismiss
    handleDismiss()
  }, [replyText, currentMessage, handleDismiss])

  // Handle keyboard in reply
  const handleReplyKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendReply()
    }
    if (e.key === 'Escape') {
      setIsReplying(false)
      setReplyText('')
    }
  }, [handleSendReply])

  if (!isVisible) return null

  // Glassmorphism styles
  const overlayStyle = isDark
    ? 'bg-slate-900/80 backdrop-blur-2xl border-white/20'
    : 'bg-white/90 backdrop-blur-2xl border-black/10 shadow-2xl'

  const textColor = isDark ? 'text-white' : 'text-slate-900'
  const mutedColor = isDark ? 'text-white/60' : 'text-slate-500'

  const buttonPrimary = 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'

  const buttonSecondary = isDark
    ? 'bg-white/10 text-white/80 hover:bg-white/20'
    : 'bg-slate-100 text-slate-700 hover:bg-slate-200'

  return (
    <>
      {/* Backdrop (subtle) */}
      <div
        className={`fixed inset-0 z-40 transition-opacity duration-300 ${
          isExiting ? 'opacity-0' : 'opacity-100'
        }`}
        style={{ background: 'transparent', pointerEvents: 'none' }}
      />

      {/* Chat Overlay - Slide in from right */}
      <div
        className={`fixed top-20 right-6 z-50 w-96 max-w-[calc(100vw-3rem)] transform transition-all duration-300 ease-out ${
          isExiting
            ? 'translate-x-full opacity-0'
            : 'translate-x-0 opacity-100'
        }`}
      >
        <div className={`rounded-3xl border p-5 ${overlayStyle}`}>
          {/* Header */}
          <div className="flex items-start justify-between mb-4">
            <div className="flex items-center gap-3">
              {/* Avatar */}
              <div className={`w-12 h-12 rounded-2xl flex items-center justify-center text-lg font-semibold ${
                isDark ? 'bg-gradient-to-br from-purple-500 to-pink-500' : 'bg-gradient-to-br from-purple-400 to-pink-400'
              } text-white`}>
                {currentMessage?.senderInitials}
              </div>
              <div>
                <h3 className={`font-semibold ${textColor}`}>
                  {currentMessage?.senderName}
                </h3>
                <p className={`text-xs ${mutedColor}`}>
                  {currentMessage?.isGroup ? 'Gruppenchat' : 'Direktnachricht'} • Jetzt
                </p>
              </div>
            </div>

            {/* Close button */}
            <button
              onClick={handleDismiss}
              className={`p-2 rounded-xl transition-colors ${
                isDark ? 'hover:bg-white/10 text-white/60' : 'hover:bg-slate-100 text-slate-400'
              }`}
            >
              <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>
          </div>

          {/* Message Content with Typewriter Effect */}
          <div className={`mb-4 p-4 rounded-2xl ${
            isDark ? 'bg-white/5' : 'bg-slate-50'
          }`}>
            <p className={`text-sm leading-relaxed ${textColor}`}>
              {displayedText}
              {isTyping && (
                <span className={`inline-block w-0.5 h-4 ml-0.5 animate-pulse ${
                  isDark ? 'bg-purple-400' : 'bg-purple-600'
                }`} />
              )}
            </p>
          </div>

          {/* Reply Input (when replying) */}
          {isReplying && (
            <div className="mb-4">
              <textarea
                value={replyText}
                onChange={(e) => setReplyText(e.target.value)}
                onKeyDown={handleReplyKeyDown}
                placeholder="Antwort schreiben..."
                autoFocus
                rows={2}
                className={`w-full px-4 py-3 rounded-xl border text-sm resize-none transition-all focus:outline-none focus:ring-2 ${
                  isDark
                    ? 'bg-white/10 border-white/20 text-white placeholder-white/40 focus:ring-purple-500/50'
                    : 'bg-white border-slate-200 text-slate-900 placeholder-slate-400 focus:ring-purple-500/50'
                }`}
              />
              <p className={`text-xs mt-1 ${mutedColor}`}>
                Enter zum Senden • Esc zum Abbrechen
              </p>
            </div>
          )}

          {/* Action Buttons */}
          <div className="flex items-center gap-2">
            {isReplying ? (
              <>
                <button
                  onClick={handleSendReply}
                  disabled={!replyText.trim()}
                  className={`flex-1 py-2.5 rounded-xl font-medium transition-all disabled:opacity-50 ${buttonPrimary}`}
                >
                  <span className="flex items-center justify-center gap-2">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                    </svg>
                    Senden
                  </span>
                </button>
                <button
                  onClick={() => { setIsReplying(false); setReplyText('') }}
                  className={`px-4 py-2.5 rounded-xl font-medium transition-all ${buttonSecondary}`}
                >
                  Abbrechen
                </button>
              </>
            ) : (
              <>
                <button
                  onClick={handleReplyClick}
                  className={`flex-1 py-2.5 rounded-xl font-medium transition-all ${buttonPrimary}`}
                >
                  <span className="flex items-center justify-center gap-2">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                    </svg>
                    Antworten
                  </span>
                </button>
                <button
                  onClick={handleOpenConversation}
                  className={`px-4 py-2.5 rounded-xl font-medium transition-all ${buttonSecondary}`}
                >
                  Öffnen
                </button>
                <button
                  onClick={handleDismiss}
                  className={`px-4 py-2.5 rounded-xl font-medium transition-all ${buttonSecondary}`}
                >
                  Später
                </button>
              </>
            )}
          </div>
        </div>

        {/* Message Queue Indicator */}
        {messageQueue.length > 0 && (
          <div className={`mt-2 px-4 py-2 rounded-xl text-center text-sm ${
            isDark ? 'bg-purple-500/20 text-purple-300' : 'bg-purple-100 text-purple-700'
          }`}>
            +{messageQueue.length} weitere Nachricht{messageQueue.length > 1 ? 'en' : ''}
          </div>
        )}
      </div>

      {/* CSS for animations */}
      <style jsx>{`
        @keyframes slideIn {
          from {
            transform: translateX(100%);
            opacity: 0;
          }
          to {
            transform: translateX(0);
            opacity: 1;
          }
        }

        @keyframes pulse {
          0%, 100% {
            opacity: 1;
          }
          50% {
            opacity: 0;
          }
        }

        .animate-pulse {
          animation: pulse 0.8s ease-in-out infinite;
        }
      `}</style>
    </>
  )
}

// Export a function to trigger messages programmatically
export function useChatOverlay() {
  // This would be connected to a global state or event system
  // For now, return a placeholder
  return {
    showMessage: (message: Omit<ChatMessage, 'id' | 'timestamp'>) => {
      console.log('Would show message:', message)
      // TODO: Implement global message trigger
    }
  }
}
