'use client'

import { useState, useRef, useEffect } from 'react'
import { useLanguage } from '@/lib/LanguageContext'
import { useTheme } from '@/lib/ThemeContext'
import { Language } from '@/lib/i18n'

interface LanguageDropdownProps {
  className?: string
}

export function LanguageDropdown({ className = '' }: LanguageDropdownProps) {
  const { language, setLanguage, schoolLanguage, setSchoolLanguage, availableLanguages } = useLanguage()
  const { isDark } = useTheme()
  const [isOpen, setIsOpen] = useState(false)
  const [mode, setMode] = useState<'native' | 'school'>('native')
  const dropdownRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  useEffect(() => {
    function handleEscape(event: KeyboardEvent) {
      if (event.key === 'Escape') setIsOpen(false)
    }
    document.addEventListener('keydown', handleEscape)
    return () => document.removeEventListener('keydown', handleEscape)
  }, [])

  const nativeLang = availableLanguages[language]
  const schoolLang = availableLanguages[schoolLanguage]
  const activeLang = mode === 'native' ? language : schoolLanguage

  const handleSelect = (lang: Language) => {
    if (mode === 'native') {
      setLanguage(lang)
    } else {
      setSchoolLanguage(lang)
    }
    setIsOpen(false)
  }

  return (
    <div ref={dropdownRef} className={`relative ${className}`}>
      {/* Trigger: shows both native + school language */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={`flex items-center gap-2 px-4 py-2.5 backdrop-blur-xl border rounded-2xl transition-all ${
          isDark
            ? 'bg-white/10 border-white/20 text-white hover:bg-white/20'
            : 'bg-black/5 border-black/10 text-slate-700 hover:bg-black/10'
        }`}
        aria-haspopup="listbox"
        aria-expanded={isOpen}
      >
        <span className="text-lg">{nativeLang?.flag}</span>
        <span className="text-sm font-medium hidden sm:inline">{nativeLang?.name}</span>
        {schoolLanguage !== language && (
          <span className={`text-xs px-1.5 py-0.5 rounded ${isDark ? 'bg-white/10 text-white/50' : 'bg-slate-200 text-slate-500'}`}>
            🏫 {schoolLang?.flag}
          </span>
        )}
        <svg
          className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''} ${isDark ? 'text-white/60' : 'text-slate-500'}`}
          fill="none" stroke="currentColor" viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {/* Dropdown */}
      {isOpen && (
        <div className={`absolute right-0 mt-2 w-56 backdrop-blur-2xl border rounded-2xl shadow-xl overflow-hidden z-50 ${
          isDark ? 'bg-slate-900/90 border-white/20' : 'bg-white/95 border-black/10'
        }`}>
          {/* Tab switcher: Muttersprache / Schulsprache */}
          <div className={`flex border-b ${isDark ? 'border-white/10' : 'border-slate-200'}`}>
            <button
              onClick={() => setMode('native')}
              className={`flex-1 py-2.5 text-xs font-medium transition-all ${
                mode === 'native'
                  ? isDark ? 'bg-white/10 text-white' : 'bg-blue-50 text-blue-700'
                  : isDark ? 'text-white/50 hover:text-white/70' : 'text-slate-400 hover:text-slate-600'
              }`}
            >
              🌍 Muttersprache
            </button>
            <button
              onClick={() => setMode('school')}
              className={`flex-1 py-2.5 text-xs font-medium transition-all ${
                mode === 'school'
                  ? isDark ? 'bg-white/10 text-white' : 'bg-blue-50 text-blue-700'
                  : isDark ? 'text-white/50 hover:text-white/70' : 'text-slate-400 hover:text-slate-600'
              }`}
            >
              🏫 Schulsprache
            </button>
          </div>

          {/* Language list */}
          <ul role="listbox" className="py-1 max-h-72 overflow-y-auto">
            {(Object.keys(availableLanguages) as Language[]).map((lang) => {
              const langInfo = availableLanguages[lang]
              const isSelected = lang === activeLang
              return (
                <li key={lang}>
                  <button
                    onClick={() => handleSelect(lang)}
                    className={`w-full flex items-center gap-3 px-4 py-2.5 text-left transition-all ${
                      isSelected
                        ? isDark ? 'bg-white/20 text-white' : 'bg-indigo-100 text-slate-900'
                        : isDark ? 'text-white/80 hover:bg-white/10' : 'text-slate-700 hover:bg-slate-100'
                    }`}
                    role="option"
                    aria-selected={isSelected}
                  >
                    <span className="text-lg">{langInfo.flag}</span>
                    <span className="text-sm font-medium">{langInfo.name}</span>
                    {isSelected && (
                      <svg className={`w-4 h-4 ml-auto ${isDark ? 'text-green-400' : 'text-green-600'}`} fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    )}
                  </button>
                </li>
              )
            })}
          </ul>
        </div>
      )}
    </div>
  )
}
