'use client'

import React, { useState, useRef, useEffect } from 'react'
import Link from 'next/link'
import { SearchIcon, ChevronDownIcon, MenuIcon, XIcon } from 'lucide-react'

import type { Header as HeaderType } from '@/payload-types'
import type { NavCategoriesData } from '../Component.client'
import { CMSLink } from '@/components/Link'

type CategoryItem = {
  id: string | number
  title: string
  slug: string
  parent?: any | null
}

export const HeaderNav: React.FC<{ data: HeaderType | null; categories?: NavCategoriesData }> = ({
  data,
  categories,
}) => {
  const [dropdownOpen, setDropdownOpen] = useState(false)
  const [mobileOpen, setMobileOpen] = useState(false)
  const [mobileTheLoaiOpen, setMobileTheLoaiOpen] = useState(false)
  const [mobileParentOpen, setMobileParentOpen] = useState<string | null>(null)
  const dropdownRef = useRef<HTMLDivElement>(null)

  const navItems = data?.navItems || []

  const childrenByParent: Record<string, CategoryItem[]> = {}
  if (categories?.children) {
    for (const child of categories.children) {
      const parentId =
        child.parent && typeof child.parent === 'object' && 'id' in child.parent
          ? String(child.parent.id)
          : String(child.parent)
      if (!childrenByParent[parentId]) childrenByParent[parentId] = []
      childrenByParent[parentId].push(child)
    }
  }

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setDropdownOpen(false)
      }
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [])

  return (
    <>
      {/* Desktop nav */}
      <nav className="hidden md:flex gap-4 items-center">
        {navItems.map(({ link }, i) => (
          <CMSLink
            key={i}
            {...link}
            className="text-sm font-medium hover:text-primary transition-colors"
          />
        ))}

        {/* Thể Loại dropdown — always present if categories exist */}
        {categories && categories.parents.length > 0 && (
          <div
            ref={dropdownRef}
            className="relative"
            onMouseEnter={() => setDropdownOpen(true)}
            onMouseLeave={() => setDropdownOpen(false)}
          >
            <button
              className="flex items-center gap-1 text-sm font-medium hover:text-primary transition-colors"
              aria-expanded={dropdownOpen}
              aria-haspopup="true"
            >
              Thể Loại <ChevronDownIcon className="w-3.5 h-3.5" />
            </button>

            {dropdownOpen && (
              <div className="absolute top-full left-1/2 -translate-x-1/2 pt-2 w-[520px] z-50">
              <div className="bg-background border border-border rounded-xl shadow-xl p-5 grid grid-cols-2 gap-x-6">
                {categories.parents.map((parent) => {
                  const kids = childrenByParent[String(parent.id)] ?? []
                  return (
                    <div key={String(parent.id)} className="mb-4">
                      <Link
                        href={`/the-loai/${parent.slug}`}
                        className="block text-sm font-semibold text-foreground hover:text-primary mb-1.5 transition-colors"
                        onClick={() => setDropdownOpen(false)}
                      >
                        {parent.title}
                      </Link>
                      {kids.map((child) => (
                        <Link
                          key={String(child.id)}
                          href={`/the-loai/${parent.slug}/${child.slug}`}
                          className="block text-xs text-muted-foreground hover:text-foreground pl-2 py-0.5 transition-colors"
                          onClick={() => setDropdownOpen(false)}
                        >
                          › {child.title}
                        </Link>
                      ))}
                    </div>
                  )
                })}
                <div className="col-span-2 pt-2 mt-1 border-t border-border">
                  <Link
                    href="/the-loai"
                    className="text-xs text-muted-foreground hover:text-primary transition-colors"
                    onClick={() => setDropdownOpen(false)}
                  >
                    Xem tất cả thể loại →
                  </Link>
                </div>
              </div>
              </div>
            )}
          </div>
        )}

        <Link href="/search">
          <span className="sr-only">Search</span>
          <SearchIcon className="w-5 text-primary" />
        </Link>
      </nav>

      {/* Mobile hamburger */}
      <div className="flex md:hidden items-center gap-3">
        <Link href="/search">
          <SearchIcon className="w-5 text-primary" />
        </Link>
        <button
          onClick={() => setMobileOpen(!mobileOpen)}
          aria-label="Toggle menu"
          className="p-1"
        >
          {mobileOpen ? <XIcon className="w-6 h-6" /> : <MenuIcon className="w-6 h-6" />}
        </button>
      </div>

      {/* Mobile menu */}
      {mobileOpen && (
        <div className="md:hidden fixed inset-0 top-[73px] bg-background border-t border-border z-40 overflow-y-auto">
          <div className="container py-6 flex flex-col gap-1">
            {navItems.map(({ link }, i) => (
              <CMSLink
                key={i}
                {...link}
                className="text-sm font-medium hover:text-primary transition-colors py-1"
                // Close menu on click handled via navigation
              />
            ))}

            {/* Thể Loại accordion */}
            {categories && categories.parents.length > 0 && (
              <>
                <button
                  onClick={() => setMobileTheLoaiOpen(!mobileTheLoaiOpen)}
                  className="flex items-center justify-between text-sm font-medium hover:text-primary transition-colors py-1"
                >
                  Thể Loại
                  <ChevronDownIcon
                    className={`w-4 h-4 transition-transform ${mobileTheLoaiOpen ? 'rotate-180' : ''}`}
                  />
                </button>

                {mobileTheLoaiOpen && (
                  <div className="pl-4 flex flex-col gap-1 border-l border-border ml-1">
                    {categories.parents.map((parent) => {
                      const kids = childrenByParent[String(parent.id)] ?? []
                      const isOpen = mobileParentOpen === String(parent.id)
                      return (
                        <div key={String(parent.id)}>
                          <div className="flex items-center justify-between">
                            <Link
                              href={`/the-loai/${parent.slug}`}
                              className="text-sm font-medium hover:text-primary transition-colors py-1 flex-1"
                              onClick={() => setMobileOpen(false)}
                            >
                              {parent.title}
                            </Link>
                            {kids.length > 0 && (
                              <button
                                onClick={() =>
                                  setMobileParentOpen(isOpen ? null : String(parent.id))
                                }
                                className="p-1"
                              >
                                <ChevronDownIcon
                                  className={`w-3.5 h-3.5 transition-transform ${isOpen ? 'rotate-180' : ''}`}
                                />
                              </button>
                            )}
                          </div>
                          {isOpen && kids.length > 0 && (
                            <div className="pl-3 flex flex-col gap-0.5 border-l border-border ml-1">
                              {kids.map((child) => (
                                <Link
                                  key={String(child.id)}
                                  href={`/the-loai/${parent.slug}/${child.slug}`}
                                  className="text-xs text-muted-foreground hover:text-foreground py-1 transition-colors"
                                  onClick={() => setMobileOpen(false)}
                                >
                                  {child.title}
                                </Link>
                              ))}
                            </div>
                          )}
                        </div>
                      )
                    })}
                    <Link
                      href="/the-loai"
                      className="text-xs text-primary py-1"
                      onClick={() => setMobileOpen(false)}
                    >
                      Xem tất cả →
                    </Link>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      )}
    </>
  )
}
