"use client"

import { useState, useRef, useEffect } from 'react'
import { useLocale } from 'next-intl'
import { usePathname, useRouter } from 'next/navigation'
import { ChevronDown } from 'lucide-react'

export default function LocaleSwitcher() {
  const locale = useLocale()
  const pathname = usePathname()
  const router = useRouter()
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  const switchLocale = (newLocale: string) => {
    // Remove current locale from pathname if present
    const pathnameWithoutLocale = pathname.replace(/^\/(en|es)/, '') || '/'
    
    // Construct new path with locale
    const newPath = `/${newLocale}${pathnameWithoutLocale === '/' ? '' : pathnameWithoutLocale}`
    
    // Set cookie for persistence (next-intl middleware will read this)
    document.cookie = `NEXT_LOCALE=${newLocale};path=/;max-age=31536000;SameSite=Lax`
    
    setIsOpen(false)
    router.push(newPath)
    router.refresh()
  }

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside)
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [isOpen])

  const locales = [
    { code: 'en', label: 'English', icon: '/images/english.webp' },
    { code: 'es', label: 'Español', icon: '/images/spanish.webp' }
  ]

  const currentLocale = locales.find(l => l.code === locale) || locales[0]
  const otherLocales = locales.filter(l => l.code !== locale)

  return (
    <div className="relative" ref={dropdownRef}>
      {/* Current Language Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 px-3 py-2 rounded-xl border border-[#0087FF]/30 bg-[#0087FF]/10 hover:bg-[#0087FF]/20 hover:border-[#0087FF]/50 transition-all duration-200 group"
        aria-label="Change language"
      >
        <div className="relative w-6 h-6 rounded overflow-hidden border border-white/20 shadow-sm">
          <img
            src={currentLocale.icon}
            alt={currentLocale.label}
            className="w-full h-full object-cover"
          />
        </div>
        <span className="text-sm font-medium text-[#8ab4ff] group-hover:text-white transition-colors hidden sm:inline-block">
          {currentLocale.code.toUpperCase()}
        </span>
        <ChevronDown 
          className={`w-4 h-4 text-[#8ab4ff] group-hover:text-white transition-all duration-200 flex-shrink-0 ${
            isOpen ? 'rotate-180' : ''
          }`} 
        />
      </button>

      {/* Dropdown Menu */}
      {isOpen && (
        <div className="absolute top-full left-0 mt-2 min-w-[180px] bg-gradient-to-br from-[#0f1620] to-[#0c1320] rounded-xl border border-[#0087FF]/30 shadow-xl shadow-black/50 backdrop-blur-md overflow-hidden z-50 animate-in fade-in slide-in-from-top-2 duration-200">
          <div className="py-1">
            {otherLocales.map((loc) => (
              <button
                key={loc.code}
                onClick={() => switchLocale(loc.code)}
                className="w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-[#0087FF]/20 transition-colors group"
              >
                <div className="relative w-7 h-7 rounded overflow-hidden border border-white/20 shadow-sm flex-shrink-0">
                  <img
                    src={loc.icon}
                    alt={loc.label}
                    className="w-full h-full object-cover"
                  />
                </div>
                <div className="flex flex-col">
                  <span className="text-sm font-medium text-white group-hover:text-[#8ab4ff] transition-colors">
                    {loc.label}
                  </span>
                  <span className="text-xs text-gray-400">
                    {loc.code.toUpperCase()}
                  </span>
                </div>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

