'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import { useTranslations, useLocale } from 'next-intl';
import { useRouter } from 'next/navigation';
import { locales } from '@/config';

export default function Header() {
  const [isLanguageOpen, setIsLanguageOpen] = useState(false);
  const [isMoreOpen, setIsMoreOpen] = useState(false);
  const moreDropdownRef = useRef<HTMLDivElement>(null);
  const languageDropdownRef = useRef<HTMLDivElement>(null);
  const pathname = usePathname();
  const t = useTranslations('Navigation');
  const tLang = useTranslations('LanguageSwitcher');
  const tCommon = useTranslations('Common');
  const locale = useLocale();
  const router = useRouter();

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (moreDropdownRef.current && !moreDropdownRef.current.contains(event.target as Node)) {
        setIsMoreOpen(false);
      }
    };

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

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

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (languageDropdownRef.current && !languageDropdownRef.current.contains(event.target as Node)) {
        setIsLanguageOpen(false);
      }
    };

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

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

  const handleLocaleChange = (newLocale: string) => {
    const newPath = `/${newLocale}${pathname.startsWith(`/${locale}`) ? pathname.substring(locale.length + 1) : pathname}`;
    router.replace(newPath);
    setIsLanguageOpen(false);
  };

  const handleContactClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    e.preventDefault();
    const footer = document.getElementById('footer-section');
    if (footer) {
      footer.scrollIntoView({ behavior: 'smooth' });
    }
  };

  const navItems = [
    { key: 'home', path: '/' },
    { key: 'about', path: '/about' },
    { key: 'location', path: '/location' },
    { key: 'team', path: '/team' },
    { key: 'investors', path: '/investors' },
    { key: 'media', path: '/media' },
    { key: 'contact', path: '#footer-section' },
  ];

  const moreItems = [
    { key: 'characteristics', path: '/characteristics' },
    { key: 'villas_layout', path: '/villas-layout' },
    { key: 'safety_resilience', path: '/safety-resilience' },
    { key: 'environmental_sustainability', path: '/environmental-sustainability' },
    { key: 'reasons_to_invest', path: '/reasons-to-invest' },
  ];

  const getLocalizedPath = (path: string) => {
    if (path === '/') {
        return `/${locale}`;
    }
    return `/${locale}${path}`;
  }

  const isActive = (path: string) => {
    const localizedPath = getLocalizedPath(path);
    if (path === '/') {
      return pathname === `/${locale}` || pathname === `/${locale}/` || pathname === '/';
    }
    return pathname === localizedPath || pathname.startsWith(localizedPath + '/');
  }

  return (
    <header className="w-full h-[65px] bg-white px-8 flex items-center justify-between">
      {/* Left: Logo */}
      <div className="w-[65px] h-[65px] flex-shrink-0">
        <Link href={getLocalizedPath('/')} className="w-full h-full relative block">
          <Image
            src="/images/logo/logotype.svg"
            alt="LAKE Resort Residence"
            fill
            sizes="65px"
            className="object-contain"
            style={{ color: "#2C2C2C" }}
            priority
          />
        </Link>
      </div>

      {/* Center: Navigation */}
      <nav className="flex items-center gap-6">
        {navItems.map((item) => (
          <div key={item.path} className="flex flex-col items-center gap-[2px]">
            <Link
              href={item.path.startsWith('#') ? item.path : getLocalizedPath(item.path)}
              onClick={item.path.startsWith('#') ? handleContactClick : undefined}
              className={`px-2 py-2 font-roboto text-lg font-medium leading-[150%] transition-colors whitespace-nowrap ${
                isActive(item.path) && !item.path.startsWith('#') ? 'text-[#2C2C2C]' : 'text-[#666] hover:text-[#2C2C2C]'
              }`}
            >
              {t(item.key)}
            </Link>
            {isActive(item.path) && !item.path.startsWith('#') && (
              <div className="w-[51px] h-[1px] bg-[#2C2C2C]" />
            )}
          </div>
        ))}

        {/* More Dropdown */}
        <div className="relative" ref={moreDropdownRef}>
          <button
            onClick={() => setIsMoreOpen(!isMoreOpen)}
            className="flex items-center gap-2 px-4 py-2 rounded-lg transition-colors whitespace-nowrap text-[#666] hover:text-[#2C2C2C]"
          >
            <span className="font-roboto text-lg font-medium leading-[150%]">{t('more')}</span>
            <svg className="w-4 h-4" 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>
          {isMoreOpen && (
            <div className="absolute top-full left-0 mt-1 w-[247px] bg-white rounded-lg shadow-lg py-2 z-[9999] transition-all duration-300 ease-out opacity-100 scale-100 translate-y-0 animate-slideDownFadeInMenu">
              {moreItems.map((item) => (
                <Link
                  key={item.path}
                  href={getLocalizedPath(item.path)}
                  className="flex px-3 py-2 text-[#2C2C2C] font-roboto text-lg font-light hover:bg-gray-50 transition-colors"
                  onClick={() => setIsMoreOpen(false)}
                >
                  {t(item.key)}
                </Link>
              ))}
            </div>
          )}
        </div>

        {/* LAKE TOKEN */}
        <div className="flex flex-col items-center gap-[2px]">
          <Link
            href={getLocalizedPath('/lake-token')}
            className="flex items-center gap-2 px-2 py-[7px] transition-colors whitespace-nowrap"
          >
            <div className="w-7 h-7 relative">
              <Image
                src="/images/logo/icon.png"
                alt="LAKE TOKEN"
                fill
                sizes="28px"
                className="object-contain"
              />
            </div>
            <span className="text-[#002F5E] font-roboto text-lg font-semibold leading-[150%]">
              {tCommon('lake_token')}
            </span>
          </Link>
          {isActive('/lake-token') && (
            <div className="w-8 h-[1px] bg-[#002F5E]" />
          )}
        </div>
      </nav>

      {/* Right: Language Switcher */}
      <div className="relative" ref={languageDropdownRef}>
        <button
          onClick={() => setIsLanguageOpen(!isLanguageOpen)}
          className="w-[77px] h-[43px] bg-white rounded-lg flex items-center justify-center gap-2 px-4 py-2 hover:bg-gray-50 transition-colors"
        >
          <span className="text-[#666] font-roboto text-lg font-medium leading-[150%]">
            {locale === 'ru' ? 'РУС' : locale === 'en' ? 'ENG' : locale === 'ar' ? 'العربية' : locale === 'zh' ? '中文' : locale.toUpperCase()}
          </span>
          <svg className="w-4 h-4" 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>
        {isLanguageOpen && (
          <div className="absolute right-0 mt-2 w-40 bg-white rounded-lg shadow-lg py-2 z-[9999] animate-slideDownFadeInMenu">
            {locales.map((lng: string) => (
              <button
                key={lng}
                onClick={() => handleLocaleChange(lng)}
                className={`w-full px-4 py-2 text-left font-roboto text-lg hover:bg-gray-50 ${
                  locale === lng ? 'font-medium text-[#2C2C2C]' : 'font-light text-[#666]'
                }`}
              >
                {lng === 'ru' ? 'РУС' : lng === 'en' ? 'ENG' : lng === 'ar' ? 'العربية' : lng === 'zh' ? '中文' : lng.toUpperCase()}
              </button>
            ))}
          </div>
        )}
      </div>
    </header>
  );
}
