import { useEffect, useState, type MouseEvent } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { ChevronDown, Menu, Search, ShoppingCart, User, X } from 'lucide-react'
import logo from '../assets/images/logo.png'
import { listCategories } from '../lib/api'
import type { CategoryNode } from '../lib/types'
import {
  consumeAuthHashFromUrl,
  displayName,
  getAuthUser,
  getCustomerDashboardUrl,
  getCustomerLoginUrl,
  type AuthUser,
} from '../lib/auth'
import { getCartCount, openCartDrawer, subscribeCart } from '../lib/cart'
import './Header.css'

const NAV_LINKS = [
  { to: '/', label: 'صفحه اصلی' },
  { to: '/products', label: 'محصولات', hasDropdown: true },
  { to: '/about-us', label: 'درباره ما' },
  { to: '/contact-us', label: 'تماس با ما' },
  { to: '/quick-info', label: 'اطلاعات مجموعه' },
]

function isActivePath(pathname: string, to: string) {
  return to === '/' ? pathname === '/' : pathname === to || pathname.startsWith(`${to}/`)
}

export default function Header() {
  const { pathname } = useLocation()
  const [mobileOpen, setMobileOpen] = useState(false)
  const [topCategories, setTopCategories] = useState<CategoryNode[]>([])
  const [user, setUser] = useState<AuthUser | null>(() => getAuthUser())
  const [cartCount, setCartCount] = useState(() => getCartCount())

  useEffect(() => {
    consumeAuthHashFromUrl()
    setUser(getAuthUser())
  }, [])

  useEffect(() => subscribeCart(() => setCartCount(getCartCount())), [])

  useEffect(() => {
    listCategories()
      .then((nodes) => setTopCategories(nodes.filter((n) => !n.parentId)))
      .catch(() => setTopCategories([]))
  }, [])

  function handleUserClick(e: MouseEvent) {
    e.preventDefault()
    if (user) {
      window.location.assign(getCustomerDashboardUrl('/'))
      return
    }
    window.location.assign(getCustomerLoginUrl(`${window.location.origin}/`))
  }

  return (
    <header className="site-header">
      <div className="max-container">
        <div className="site-header__inner">
          <Link to="/" className="site-header__logo" onClick={() => setMobileOpen(false)}>
            <img src={logo} alt="لوگو" width={60} height={68} />
          </Link>

          <nav className="site-header__nav">
            <ul>
              {NAV_LINKS.map((link) => {
                const active = isActivePath(pathname, link.to)
                if (link.hasDropdown) {
                  return (
                    <li key={link.to} className="site-header__dropdown">
                      <Link
                        to={link.to}
                        className={`menu-link${active ? ' active-link' : ''}`}
                        aria-haspopup="true"
                      >
                        <span className="menu-link__label">
                          {link.label}
                          <ChevronDown className="menu-chevron" size={12} />
                        </span>
                      </Link>
                      <div className="site-header__dropdown-panel">
                        <div className="site-header__dropdown-inner">
                          <Link
                            to="/products"
                            className="site-header__dropdown-item"
                          >
                            همه محصولات
                          </Link>
                          {topCategories.map((cat) => (
                            <Link
                              key={cat.id}
                              to={`/products/${cat.slug}`}
                              className="site-header__dropdown-item"
                            >
                              {cat.nameFa}
                            </Link>
                          ))}
                        </div>
                      </div>
                    </li>
                  )
                }

                return (
                  <li key={link.to}>
                    <Link
                      to={link.to}
                      className={`menu-link${active ? ' active-link' : ''}`}
                    >
                      <span className="menu-link__label">{link.label}</span>
                    </Link>
                  </li>
                )
              })}
            </ul>
          </nav>

          <div className="site-header__actions">
            <button
              type="button"
              className="site-header__cart"
              aria-label="سبد خرید"
              onClick={() => openCartDrawer()}
            >
              <ShoppingCart size={22} strokeWidth={1.5} />
              {cartCount > 0 && (
                <span className="site-header__cart-badge">
                  {cartCount.toLocaleString('fa-IR')}
                </span>
              )}
            </button>
            <Link to="/search" aria-label="جستجو">
              <Search size={22} strokeWidth={1.5} />
            </Link>
            <a
              href={user ? getCustomerDashboardUrl('/') : getCustomerLoginUrl(`${window.location.origin}/`)}
              className="site-header__user"
              aria-label={user ? 'پنل کاربری' : 'ورود'}
              onClick={handleUserClick}
            >
              <User size={22} strokeWidth={1.5} />
              {user && <span className="site-header__user-name">{displayName(user)}</span>}
            </a>
            <button
              type="button"
              className="site-header__burger"
              aria-label="منو"
              onClick={() => setMobileOpen((v) => !v)}
            >
              {mobileOpen ? <X size={24} strokeWidth={1.5} /> : <Menu size={24} strokeWidth={1.5} />}
            </button>
          </div>
        </div>

        {mobileOpen && (
          <nav className="site-header__mobile">
            <ul>
              {NAV_LINKS.map((link) => {
                const active = isActivePath(pathname, link.to)
                return (
                  <li key={link.to}>
                    <Link
                      to={link.to}
                      className={`menu-link${active ? ' active-link' : ''}`}
                      onClick={() => setMobileOpen(false)}
                    >
                      <span className="menu-link__label">{link.label}</span>
                    </Link>
                    {link.hasDropdown && (
                      <ul className="site-header__mobile-sub">
                        <li>
                          <Link to="/products" onClick={() => setMobileOpen(false)}>
                            همه محصولات
                          </Link>
                        </li>
                        {topCategories.map((cat) => (
                          <li key={cat.id}>
                            <Link
                              to={`/products/${cat.slug}`}
                              onClick={() => setMobileOpen(false)}
                            >
                              {cat.nameFa}
                            </Link>
                          </li>
                        ))}
                      </ul>
                    )}
                  </li>
                )
              })}
              <li>
                <a
                  href={user ? getCustomerDashboardUrl('/') : getCustomerLoginUrl(`${window.location.origin}/`)}
                  className="site-header__mobile-user"
                  onClick={(e) => {
                    setMobileOpen(false)
                    handleUserClick(e)
                  }}
                >
                  <User size={18} strokeWidth={1.5} />
                  {user ? displayName(user) : 'ورود'}
                </a>
              </li>
            </ul>
          </nav>
        )}
      </div>
    </header>
  )
}
