'use client'

import { useLocale } from 'next-intl'
import { usePathname, useRouter } from '@/i18n/navigation'
import { routing } from '@/i18n/routing'
import { useState, useRef, useEffect } from 'react'
import { useClickOutside } from '@/app/hooks/useClickOutside';

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

	const switchLanguage = (newLocale: string) => {
		const currentLang = document.documentElement.getAttribute('lang') || 'ru';
		router.replace(pathname, { locale: newLocale });
		setIsOpen(false);

		const observer = new MutationObserver((mutations) => {
			const newLang = document.documentElement.getAttribute('lang')

			if (newLang && newLang !== currentLang) {
				observer.disconnect();

				if (window.location.protocol === 'http:' && process.env.NODE_ENV !== 'development') {
					setTimeout(() => window.location.reload(), 100)
				}
			}
		})

		if (window.location.protocol === 'http:' && process.env.NODE_ENV !== 'development') {
			observer.observe(document.documentElement, {
				attributes: true,
				attributeFilter: ['lang', 'dir']
			})
		}

		router.replace(pathname, { locale: newLocale })

		setTimeout(() => {
			observer.disconnect();
		}, 3000)
	}

	useClickOutside(dropdownRef, () => {
		setIsOpen(false);
	});

	useEffect(() => {
		const handleEscape = (event: KeyboardEvent) => {
			if (event.key === 'Escape') setIsOpen(false)
		}

		document.addEventListener('keydown', handleEscape)
		return () => document.removeEventListener('keydown', handleEscape)
	}, []);

	return (
		<div className="language-switcher" ref={dropdownRef}>
			<button
				onClick={() => setIsOpen(!isOpen)}
				className="switcher-btn"
			>
				<span className="flex items-center">
					<span className="mr-2">{locale === 'ru' ? 'РУ' : locale.toUpperCase()}</span>
				</span>
				<svg
					className={`w-5 h-5 ml-2 transition-transform ${isOpen ? 'rotate-180' : ''}`}
					xmlns="http://www.w3.org/2000/svg"
					viewBox="0 0 20 20"
					fill="currentColor"
				>
					<path
						fillRule="evenodd"
						d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
						clipRule="evenodd"
					/>
				</svg>
			</button>

			{isOpen && (
				<div className="switcher-list">
					<ul
						className="py-1"
						role="listbox"
						aria-labelledby="language-selector"
					>
						{routing.locales.map((lang) => (
							<li key={lang} role="option">
								<button
									onClick={() => switchLanguage(lang)}
									className={`language-btn ${locale === lang ? 'active' : ''
										}`}
									role="menuitem"
								>
									<span className="mr-2 font-medium">
										{lang === 'ru' ? 'РУ' : lang.toUpperCase()}
									</span>
								</button>
							</li>
						))}
					</ul>
				</div>
			)}
		</div>
	)
}