'use client'

import { useState, useRef, useEffect } from 'react'
import Link from 'next/link'
import { Menu, X, Search, ChevronDown, Phone, Mail, MapPin, ExternalLink } from 'lucide-react'
import { useSettings } from '@/lib/hooks'
import { getImageUrl } from '@/lib/images'
import { getMenu } from '@/lib/api'

interface NavMenuItem {
  id: number
  label: string
  url: string
  type: string
  target: string
  icon: string | null
  children: NavMenuItem[]
}

const fallbackNav: NavMenuItem[] = [
  { id: 1, label: 'Beranda', url: '/', type: 'custom', target: '_self', icon: null, children: [] },
  { id: 2, label: 'Profil', url: '/profil', type: 'custom', target: '_self', icon: null, children: [
    { id: 20, label: 'Profil Kabupaten', url: '/profil', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 21, label: 'Profil Bupati', url: '/profil/bupati', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 22, label: 'Profil Wakil Bupati', url: '/profil/wakil-bupati', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 23, label: 'Sambutan Bupati', url: '/profil/sambutan-bupati', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 24, label: 'Sambutan Wakil Bupati', url: '/profil/sambutan-wakil-bupati', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 25, label: 'Visi Misi', url: '/profil/visi-misi', type: 'custom', target: '_self', icon: null, children: [] },
  ]},
  { id: 3, label: 'Pemerintahan', url: '/pemerintahan', type: 'custom', target: '_self', icon: null, children: [
    { id: 30, label: 'OPD', url: '/pemerintahan/opd', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 31, label: 'Kecamatan', url: '/pemerintahan/kecamatan', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 32, label: 'Desa/Kelurahan', url: '/pemerintahan/desa', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 33, label: 'BUMD', url: '/pemerintahan/bumd', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 34, label: 'UPTD', url: '/pemerintahan/uptd', type: 'custom', target: '_self', icon: null, children: [] },
  ]},
  { id: 4, label: 'Berita', url: '/berita', type: 'custom', target: '_self', icon: null, children: [] },
  { id: 5, label: 'Informasi Publik', url: '/informasi-publik', type: 'custom', target: '_self', icon: null, children: [
    { id: 50, label: 'IPKD', url: '/informasi-publik/ipkd', type: 'custom', target: '_self', icon: null, children: [] },
  ]},
  { id: 6, label: 'Layanan Publik', url: '/layanan', type: 'custom', target: '_self', icon: null, children: [] },
  { id: 7, label: 'Statistik', url: '/statistik', type: 'custom', target: '_self', icon: null, children: [] },
  { id: 8, label: 'Agenda', url: '/agenda', type: 'custom', target: '_self', icon: null, children: [] },
  { id: 9, label: 'Pengumuman', url: '/pengumuman', type: 'custom', target: '_self', icon: null, children: [] },
  { id: 10, label: 'Media Center', url: '/media', type: 'custom', target: '_self', icon: null, children: [
    { id: 100, label: 'Foto', url: '/media/foto', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 101, label: 'Video', url: '/media/video', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 102, label: 'Foto 360', url: '/media/360', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 103, label: 'Infografis', url: '/media/infografis', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 104, label: 'Ebook', url: '/media/ebook', type: 'custom', target: '_self', icon: null, children: [] },
    { id: 105, label: 'Dokumen', url: '/media/dokumen', type: 'custom', target: '_self', icon: null, children: [] },
  ]},
  { id: 11, label: 'Live', url: '/live', type: 'custom', target: '_self', icon: null, children: [] },
  { id: 12, label: 'Kontak', url: '/kontak', type: 'custom', target: '_self', icon: null, children: [] },
]

export default function Header() {
  const [menuOpen, setMenuOpen] = useState(false)
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null)
  const [searchOpen, setSearchOpen] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [scrolled, setScrolled] = useState(false)
  const [navItems, setNavItems] = useState<NavMenuItem[]>(fallbackNav)
  const timeoutRef = useRef<NodeJS.Timeout | null>(null)
  const searchInputRef = useRef<HTMLInputElement>(null)
  const settings = useSettings()

  useEffect(() => {
    getMenu('header')
      .then((res) => {
        if (res.items && res.items.length > 0) setNavItems(res.items)
      })
      .catch(() => {})
  }, [])

  useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 10)
    window.addEventListener('scroll', handleScroll, { passive: true })
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  useEffect(() => {
    if (searchOpen && searchInputRef.current) searchInputRef.current.focus()
  }, [searchOpen])

  const handleMouseEnter = (label: string) => {
    if (timeoutRef.current) clearTimeout(timeoutRef.current)
    setActiveDropdown(label)
  }

  const handleMouseLeave = () => {
    timeoutRef.current = setTimeout(() => setActiveDropdown(null), 150)
  }

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault()
    if (searchQuery.trim()) {
      window.location.href = `/pencarian?q=${encodeURIComponent(searchQuery.trim())}`
      setSearchOpen(false)
      setSearchQuery('')
    }
  }

  const topbarQuickLinks = (() => { try { return JSON.parse(settings.topbar_quick_links || '[]') } catch { return [] } })()
  const topbarExternalLinks = (() => { try { return JSON.parse(settings.topbar_external_links || '[]') } catch { return [] } })()

  return (
    <>
      {/* Top Bar */}
      <div className="bg-[#0f2942] text-white/80 text-xs border-b border-white/5">
        <div className="max-w-7xl mx-auto px-4 flex items-center justify-between h-9">
          <div className="flex items-center gap-4">
            {settings.site_phone && (
              <span className="flex items-center gap-1.5 hover:text-[#f59e0b] transition-colors cursor-pointer"><Phone size={11} /> {settings.site_phone}</span>
            )}
            {settings.site_email && (
              <span className="flex items-center gap-1.5 hover:text-[#f59e0b] transition-colors cursor-pointer"><Mail size={11} /> {settings.site_email}</span>
            )}
            {settings.site_address && (
              <span className="hidden md:flex items-center gap-1.5"><MapPin size={11} /> {settings.site_address}</span>
            )}
          </div>
          <div className="flex items-center gap-3">
            {topbarQuickLinks.map((link: any) => (
              <Link key={link.href} href={link.href} className="hover:text-[#f59e0b] transition-colors">{link.label}</Link>
            ))}
            {topbarQuickLinks.length > 0 && topbarExternalLinks.length > 0 && <span className="text-white/20">|</span>}
            {topbarExternalLinks.map((link: any) => (
              <a key={link.href} href={link.href} target="_blank" rel="noopener" className="hover:text-[#f59e0b] flex items-center gap-0.5 transition-colors">
                {link.label} <ExternalLink size={10} />
              </a>
            ))}
          </div>
        </div>
      </div>

      {/* Main Header */}
      <header className={`bg-[#1e3a5f] text-white sticky top-0 z-50 transition-all duration-300 ${scrolled ? 'shadow-government shadow-lg' : 'shadow-md'}`}>
        <div className="max-w-7xl mx-auto px-4">
          <div className="flex items-center justify-between h-16">
            {/* Logo */}
            <Link href="/" className="flex items-center gap-3 shrink-0 group">
              {getImageUrl(settings.logo_url) ? (
                <img src={getImageUrl(settings.logo_url)!} alt={settings.site_name || 'Logo'} className="h-10 w-auto object-contain" />
              ) : (
                <div className="w-10 h-10 bg-[#c8102e] rounded-xl flex items-center justify-center font-bold text-lg shadow-lg shadow-[#c8102e]/30 group-hover:shadow-[#c8102e]/40 transition-all group-hover:scale-105">
                  B
                </div>
              )}
              <div className="hidden sm:block leading-tight">
                <div className="text-[9px] tracking-[0.2em] text-white/60 uppercase">Pemerintah Kabupaten</div>
                <div className="text-lg font-display font-bold">Buton</div>
              </div>
            </Link>

            {/* Desktop Nav */}
            <nav className="hidden lg:flex items-center gap-0.5">
              {navItems.map((item) => (
                <div key={item.id} className="relative"
                  onMouseEnter={() => item.children?.length && handleMouseEnter(item.label)}
                  onMouseLeave={handleMouseLeave}>
                  <Link
                    href={item.url}
                    target={item.target}
                    className={`px-2.5 py-2 text-[13px] font-medium rounded-lg transition-all flex items-center gap-1 ${
                      item.label === 'Live'
                        ? 'text-red-400 hover:bg-red-500/20 animate-pulse'
                        : 'hover:bg-white/10 text-white/90 hover:text-white'
                    }`}
                  >
                    {item.label}
                    {item.children?.length > 0 && <ChevronDown size={12} className={`transition-transform ${activeDropdown === item.label ? 'rotate-180' : ''}`} />}
                  </Link>

                  {item.children?.length > 0 && activeDropdown === item.label && (
                    <div className="absolute top-full left-0 bg-white text-gray-800 shadow-2xl rounded-xl py-2 min-w-[220px] z-50 border border-gray-100 animate-fade-in"
                      onMouseEnter={() => handleMouseEnter(item.label)}
                      onMouseLeave={handleMouseLeave}>
                      <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-[#1e3a5f] to-[#c8102e] rounded-t-xl" />
                      {item.children.map((child) => (
                        <Link key={child.id} href={child.url} target={child.target}
                          className="block px-4 py-2.5 text-sm hover:bg-[#1e3a5f]/5 hover:text-[#1e3a5f] transition-colors border-b border-gray-50 last:border-0">
                          {child.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </nav>

            <div className="flex items-center gap-1">
              <button onClick={() => setSearchOpen(!searchOpen)} className="p-2 hover:bg-white/10 rounded-lg transition-colors">
                <Search size={18} />
              </button>
              <button className="lg:hidden p-2 hover:bg-white/10 rounded-lg" onClick={() => setMenuOpen(!menuOpen)}>
                {menuOpen ? <X size={20} /> : <Menu size={20} />}
              </button>
            </div>
          </div>
        </div>

        {/* Search Bar */}
        {searchOpen && (
          <div className="bg-[#152d4a] border-t border-white/10 animate-fade-in">
            <div className="max-w-7xl mx-auto px-4 py-3">
              <form onSubmit={handleSearch} className="flex gap-2">
                <input
                  ref={searchInputRef}
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Cari berita, layanan, dokumen..."
                  className="flex-1 px-4 py-2.5 rounded-xl text-sm text-gray-800 outline-none focus:ring-2 focus:ring-[#f59e0b] bg-white/95"
                />
                <button type="submit" className="bg-[#c8102e] text-white px-6 py-2.5 rounded-xl text-sm font-medium hover:bg-[#a00d24] transition-colors shadow-lg shadow-[#c8102e]/25">
                  Cari
                </button>
              </form>
            </div>
          </div>
        )}

        {/* Mobile Nav */}
        {menuOpen && (
          <div className="lg:hidden bg-[#152d4a] border-t border-white/10 max-h-[70vh] overflow-y-auto animate-fade-in">
            <nav className="max-w-7xl mx-auto px-4 py-3">
              {navItems.map((item) => (
                <div key={item.id}>
                  <Link href={item.url} target={item.target}
                    className={`block py-2.5 text-sm border-b border-white/10 last:border-0 transition-colors ${
                      item.label === 'Live' ? 'text-red-400 font-medium' : 'hover:text-[#f59e0b]'
                    }`}
                    onClick={() => setMenuOpen(false)}>
                    {item.label}
                  </Link>
                  {item.children?.length > 0 && (
                    <div className="pl-4">
                      {item.children.map((child) => (
                        <Link key={child.id} href={child.url} target={child.target}
                          className="block py-2 text-xs text-white/60 border-b border-white/5 last:border-0 hover:text-[#f59e0b]"
                          onClick={() => setMenuOpen(false)}>
                          {child.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </nav>
          </div>
        )}
      </header>
    </>
  )
}
