'use client'

import { Building2, ChevronDown, Menu, Moon, Search, Sun, X } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useEffect, useRef, useState } from 'react'
import { useCarplacePreferences, localeOptions } from '@/components/CarplaceShell'
import { getCarplaceMessages } from '@/lib/carplace/messages'
import { carplaceHref, homepageHref } from '@/lib/carplace/routes'

export default function CarplaceHeader({ dashboardUrl }: { dashboardUrl: string }) {
  const { language, theme, setLanguage, setTheme } = useCarplacePreferences()
  const copy = getCarplaceMessages(language)
  const pathname = usePathname()
  const [mobileOpen, setMobileOpen] = useState(false)
  const [languageOpen, setLanguageOpen] = useState(false)
  const languageRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    setMobileOpen(false)
  }, [pathname])

  useEffect(() => {
    function closeMenus(event: MouseEvent) {
      if (!languageRef.current?.contains(event.target as Node)) setLanguageOpen(false)
    }
    document.addEventListener('mousedown', closeMenus)
    return () => document.removeEventListener('mousedown', closeMenus)
  }, [])

  const nav: Array<{ label: string; href: string; icon: typeof Search | null }> = [
    { label: copy.nav.find, href: carplaceHref('/search'), icon: Search },
    { label: copy.nav.companies, href: carplaceHref('/#companies'), icon: null },
    { label: copy.nav.deals, href: carplaceHref('/#offers'), icon: null },
    { label: copy.nav.how, href: carplaceHref('/#how-it-works'), icon: null },
    { label: copy.nav.help, href: carplaceHref('/#help'), icon: null },
  ]

  const currentLocale = localeOptions.find((item) => item.value === language) ?? localeOptions[0]

  return (
    <header className="carplace-header">
      <div className="shell flex min-h-[76px] items-center gap-4">
        <Link href={homepageHref(language)} className="flex min-w-0 items-center gap-3 text-blue-950 no-underline dark:text-white" aria-label={copy.accessibility.home}>
          <Image src="/rentaldrivego.png" alt="" width={38} height={38} className="h-[38px] w-[38px] rounded-xl object-cover" priority unoptimized />
          <span className="min-w-0">
            <span className="block truncate text-base font-black leading-tight tracking-[-0.02em]">RentalDriveGo</span>
            <span className="block truncate text-[11px] font-bold uppercase tracking-[0.2em] text-orange-600 dark:text-orange-400">{copy.brand}</span>
          </span>
        </Link>

        <nav className="mx-auto hidden items-center gap-1 lg:flex" aria-label="Carplace">
          {nav.map(({ label, href }) => (
            <Link key={href} href={href} className="rounded-xl px-3 py-2 text-sm font-semibold text-stone-700 no-underline transition hover:bg-blue-50 hover:text-blue-900 dark:text-slate-200 dark:hover:bg-blue-900/50 dark:hover:text-white">
              {label}
            </Link>
          ))}
        </nav>

        <div className="ms-auto hidden items-center gap-2 md:flex">
          <div ref={languageRef} className="relative">
            <button type="button" className="carplace-control" onClick={() => setLanguageOpen((value) => !value)} aria-expanded={languageOpen} aria-haspopup="menu">
              <span aria-hidden="true">{currentLocale.flag}</span>
              <span>{language.toUpperCase()}</span>
              <ChevronDown className={`h-4 w-4 transition ${languageOpen ? 'rotate-180' : ''}`} />
            </button>
            {languageOpen ? (
              <div className="carplace-menu end-0" role="menu">
                {localeOptions.map((option) => (
                  <button key={option.value} type="button" role="menuitem" className="carplace-menu-item" onClick={() => { setLanguage(option.value); setLanguageOpen(false) }}>
                    <span aria-hidden="true">{option.flag}</span>
                    <span>{option.label}</span>
                  </button>
                ))}
              </div>
            ) : null}
          </div>

          <button type="button" className="carplace-icon-button" onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')} aria-label={theme === 'dark' ? copy.footer.light : copy.footer.dark}>
            {theme === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
          </button>

          <a href={dashboardUrl} className="carplace-company-link">
            <Building2 className="h-4 w-4" />
            <span>{copy.actions.companySpace}</span>
          </a>
        </div>

        <button type="button" className="carplace-icon-button ms-auto md:hidden" onClick={() => setMobileOpen((value) => !value)} aria-expanded={mobileOpen} aria-label={copy.accessibility.menu}>
          {mobileOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
        </button>
      </div>

      {mobileOpen ? (
        <div className="border-t border-stone-200 bg-white px-4 pb-5 pt-3 shadow-xl dark:border-blue-900 dark:bg-blue-950 md:hidden">
          <nav className="grid gap-1" aria-label={copy.accessibility.mobileNav}>
            {nav.map(({ label, href, icon: Icon }) => (
              <Link key={href} href={href} className="flex items-center gap-3 rounded-xl px-3 py-3 text-sm font-semibold text-stone-700 no-underline hover:bg-blue-50 dark:text-slate-200 dark:hover:bg-blue-900/50">
                {Icon ? <Icon className="h-4 w-4" /> : null}
                {label}
              </Link>
            ))}
          </nav>
          <div className="mt-4 grid grid-cols-3 gap-2 border-t border-stone-200 pt-4 dark:border-blue-900">
            {localeOptions.map((option) => (
              <button key={option.value} type="button" onClick={() => setLanguage(option.value)} className={`carplace-control justify-center ${language === option.value ? 'border-orange-500 text-orange-700 dark:text-orange-300' : ''}`}>
                {option.flag} {option.value.toUpperCase()}
              </button>
            ))}
          </div>
          <div className="mt-3 grid grid-cols-[auto_1fr] gap-2">
            <button type="button" className="carplace-icon-button" onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')} aria-label={theme === 'dark' ? copy.footer.light : copy.footer.dark}>
              {theme === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
            </button>
            <a href={dashboardUrl} className="carplace-company-link justify-center"><Building2 className="h-4 w-4" />{copy.actions.companySpace}</a>
          </div>
        </div>
      ) : null}
    </header>
  )
}
