'use client'

import Link from 'next/link'
import Image from 'next/image'
import { usePathname } from 'next/navigation'
import { useState, useEffect } from 'react'
import { signOut } from 'next-auth/react'
import { useSafeSession } from '@/hooks/use-safe-session'
import { useSiteSettings } from '@/hooks/use-site-settings'
import {
  Menu, X, Home, Search, Building, MessageSquare,
  LogIn, UserPlus, Users, LogOut, LayoutDashboard, Heart, Calculator,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { NotificationBell } from '@/components/notifications/notification-bell'

const ICON_MAP: Record<string, React.ReactNode> = {
  '/': <Home className="w-4 h-4" />,
  '/search': <Search className="w-4 h-4" />,
  '/properties': <Building className="w-4 h-4" />,
  '/agents': <Users className="w-4 h-4" />,
  '/messages': <MessageSquare className="w-4 h-4" />,
  '/favorites': <Heart className="w-4 h-4" />,
  '/mortgage-calculator': <Calculator className="w-4 h-4" />,
}

const DEFAULT_LINKS = [
  { href: '/',                   label: 'الرئيسية' },
  { href: '/search',             label: 'البحث'    },
  { href: '/properties',         label: 'العقارات' },
  { href: '/agents',             label: 'الوكلاء'  },
  { href: '/mortgage-calculator',label: 'التمويل'  },
  { href: '/messages',           label: 'الرسائل'  },
  { href: '/favorites',          label: 'المفضلة'  },
]

export function Navbar() {
  const [isOpen, setIsOpen] = useState(false)
  const [scrolled, setScrolled] = useState(false)
  const pathname = usePathname()
  const { data: session, status } = useSafeSession()
  const isLoading = status === 'loading'
  const s = useSiteSettings()
  const brandName = s.navbar?.brandName || 'عقار ديزاين'
  const links = s.navbar?.links?.length ? s.navbar.links : DEFAULT_LINKS

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

  const isActive = (href: string) =>
    href === '/' ? pathname === '/' : pathname.startsWith(href)

  return (
    <nav
      className={`sticky top-0 z-50 transition-all duration-300 ${
        scrolled
          ? 'bg-white/80 backdrop-blur-xl shadow-lg shadow-black/5 border-b border-black/5'
          : 'bg-white/95 backdrop-blur-md border-b border-transparent'
      }`}
    >
      <div className="container mx-auto px-4 sm:px-6">
        <div className="flex justify-between items-center h-16">
          {/* Logo */}
          <Link href="/" className="flex items-center gap-2.5 shrink-0 group">
            <div className="w-9 h-9 bg-gradient-to-br from-blue-600 to-blue-700 rounded-xl flex items-center justify-center shadow-md shadow-blue-600/20 group-hover:shadow-lg group-hover:shadow-blue-600/30 transition-all duration-300 group-hover:scale-105">
              <Building className="w-5 h-5 text-white" />
            </div>
            <span className="text-lg font-bold bg-gradient-to-l from-blue-900 to-blue-700 bg-clip-text text-transparent">
              {brandName}
            </span>
          </Link>

          {/* Desktop nav */}
          <div className="hidden md:flex items-center gap-0.5">
{links.map((link: any) => (
                <Link
                  key={link.href}
                  href={link.href}
                  className={`relative flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                    isActive(link.href)
                      ? 'bg-blue-50 text-blue-700 shadow-sm shadow-blue-100'
                      : 'text-gray-500 hover:text-gray-900 hover:bg-gray-50'
                  }`}
                >
                  {ICON_MAP[link.href] || <Home className="w-4 h-4" /> || null}
                  {link.label}
                </Link>
              ))}
          </div>

          {/* Desktop auth */}
          <div className="hidden md:flex items-center gap-2">
            <NotificationBell userId={session?.user?.id} />

            {isLoading ? (
              <div className="w-24 h-9 bg-gray-100 rounded-lg animate-pulse" />
            ) : session ? (
              <>
                {(session.user?.role === 'AGENT' || session.user?.role === 'ADMIN') && (
                  <Button variant="ghost" size="sm" asChild>
                    <Link href="/dashboard" className="flex items-center gap-1.5">
                      <LayoutDashboard className="w-4 h-4" />
                      لوحة التحكم
                    </Link>
                  </Button>
                )}
                <div className="flex items-center gap-2 px-3 py-1.5 rounded-xl bg-gray-50/80 border border-gray-100">
                  {session.user?.image ? (
                    <Image
                      src={session.user.image}
                      alt={session.user.name ?? ''}
                      width={28}
                      height={28}
                      className="rounded-full object-cover ring-2 ring-white"
                    />
                  ) : (
                    <div className="w-7 h-7 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center text-white text-xs font-bold ring-2 ring-white">
                      {session.user?.name?.charAt(0) ?? '؟'}
                    </div>
                  )}
                  <span className="text-sm font-medium text-gray-700 max-w-[100px] truncate">
                    {session.user?.name}
                  </span>
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => signOut({ callbackUrl: '/' })}
                  className="gap-1.5 text-gray-500 hover:text-red-600 hover:bg-red-50"
                >
                  <LogOut className="w-4 h-4" />
                </Button>
              </>
            ) : (
              <>
                <Button variant="ghost" size="sm" asChild>
                  <Link href="/login" className="flex items-center gap-1.5 text-gray-600">
                    <LogIn className="w-4 h-4" />
                    تسجيل الدخول
                  </Link>
                </Button>
                <Button size="sm" asChild className="rounded-lg shadow-md shadow-blue-600/20 hover:shadow-lg hover:shadow-blue-600/30 transition-all duration-300">
                  <Link href="/register" className="flex items-center gap-1.5">
                    <UserPlus className="w-4 h-4" />
                    إنشاء حساب
                  </Link>
                </Button>
              </>
            )}
          </div>

          {/* Mobile toggle */}
          <button
            className="md:hidden p-2 rounded-lg hover:bg-gray-100 transition-colors"
            onClick={() => setIsOpen(!isOpen)}
            aria-label={isOpen ? 'إغلاق القائمة' : 'فتح القائمة'}
          >
            {isOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
          </button>
        </div>
      </div>

      {/* Mobile menu */}
      <div className={`md:hidden border-t overflow-hidden transition-all duration-300 ${
        isOpen ? 'max-h-[500px] opacity-100' : 'max-h-0 opacity-0'
      }`}>
        <div className="container mx-auto px-4 py-3 space-y-1 bg-white/95 backdrop-blur-xl">
          {links.map((link: any) => (
            <Link
              key={link.href}
              href={link.href}
              onClick={() => setIsOpen(false)}
              className={`flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 ${
                isActive(link.href)
                  ? 'bg-blue-50 text-blue-700 font-medium shadow-sm'
                  : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'
              }`}
            >
              {ICON_MAP[link.href] || <Home className="w-5 h-5" />}
              {link.label}
            </Link>
          ))}
          <div className="pt-3 border-t">
            {session ? (
              <div className="space-y-2">
                <div className="flex items-center gap-3 px-4 py-3 bg-gray-50/80 rounded-xl">
                  {session.user?.image ? (
                    <Image
                      src={session.user.image}
                      alt={session.user.name ?? ''}
                      width={36}
                      height={36}
                      className="rounded-full ring-2 ring-white"
                    />
                  ) : (
                    <div className="w-9 h-9 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center text-white text-sm font-bold ring-2 ring-white">
                      {session.user?.name?.charAt(0) ?? '؟'}
                    </div>
                  )}
                  <div>
                    <span className="block font-medium text-gray-800">{session.user?.name}</span>
                    <span className="text-xs text-gray-500">{session.user?.email}</span>
                  </div>
                </div>
                <Button
                  variant="outline"
                  className="w-full gap-2 text-red-600 border-red-200 hover:bg-red-50"
                  onClick={() => signOut({ callbackUrl: '/' })}
                >
                  <LogOut className="w-4 h-4" />
                  تسجيل الخروج
                </Button>
              </div>
            ) : (
              <div className="flex gap-2">
                <Button variant="outline" className="flex-1" asChild>
                  <Link href="/login">تسجيل الدخول</Link>
                </Button>
                <Button className="flex-1 shadow-md shadow-blue-600/20" asChild>
                  <Link href="/register">إنشاء حساب</Link>
                </Button>
              </div>
            )}
          </div>
        </div>
      </div>
    </nav>
  )
}
