"use client"

import * as React from "react"
import Link from "next/link"
import Image from "next/image"
import { usePathname, useRouter } from "next/navigation"
import { motion, AnimatePresence } from "framer-motion"
import { Menu, X, ChevronDown, User, LogOut, Settings, Heart, Bell } from "lucide-react"
import { Button } from "@/components/ui/button"
import { AnimatedButton } from "@/components/ui/animated-button"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { cn } from "@/lib/utils"
import { useAuth } from "@/hooks/use-auth"

interface HeaderProps {
  className?: string
}

const navigationItems = [
  { href: "/search", label: "Search Facilities" },
  { href: "/how-it-works", label: "How It Works" },
  { href: "/reviews", label: "Reviews" },
  { href: "/about", label: "About" },
  { href: "/resources", label: "Resources" },
]

export function Header({ className }: HeaderProps) {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = React.useState(false)
  const [isScrolled, setIsScrolled] = React.useState(false)
  const [isDropdownOpen, setIsDropdownOpen] = React.useState(false)
  const pathname = usePathname()
  const router = useRouter()
  const { user, isAuthenticated, logout, isLoading } = useAuth()
  const dropdownRef = React.useRef<HTMLDivElement>(null)

  React.useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 10)
    }

    window.addEventListener("scroll", handleScroll)
    return () => window.removeEventListener("scroll", handleScroll)
  }, [])

  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false)
      }
    }

    if (isDropdownOpen) {
      document.addEventListener('mousedown', handleClickOutside)
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [isDropdownOpen])

  const isActive = (href: string) => pathname === href

  const handleLogout = async () => {
    try {
      await logout()
      router.push('/')
    } catch (error) {
      console.error('Logout failed:', error)
    }
  }

  const getUserInitials = () => {
    if (!user) return 'U'
    return `${user.firstName?.[0] || ''}${user.lastName?.[0] || ''}`.toUpperCase()
  }

  const getUserDisplayName = () => {
    if (!user) return 'User'
    return `${user.firstName || ''} ${user.lastName || ''}`.trim()
  }

  const renderAuthSection = () => {
    if (isLoading) {
      return (
        <div className="flex items-center space-x-2">
          <div className="w-8 h-8 bg-gray-200 rounded-full animate-pulse" />
        </div>
      )
    }

    if (isAuthenticated && user) {
      return (
        <div className="flex items-center space-x-4">
          {/* Notifications (for authenticated users) */}
          <Button
            variant="ghost"
            size="sm"
            className="relative p-2"
            onClick={() => router.push('/notifications')}
          >
            <Bell className="h-5 w-5" />
            {/* Notification badge */}
            <span className="absolute -top-1 -right-1 h-3 w-3 bg-red-500 rounded-full text-xs" />
          </Button>

          {/* User Profile Dropdown */}
          <div className="relative" ref={dropdownRef}>
            <Button
              variant="ghost"
              className="flex items-center space-x-2 p-2 hover:bg-gray-100 rounded-lg"
              type="button"
              onClick={() => setIsDropdownOpen(!isDropdownOpen)}
            >
              <Avatar className="h-8 w-8" key={(user as any)?.profilePicture || (user as any)?.profile?.profilePicture || 'avatar'}>
                <AvatarImage
                  src={(user as any)?.profilePicture || (user as any)?.profile?.profilePicture || ''}
                  alt={getUserDisplayName()}
                />
                <AvatarFallback className="bg-blue-600 text-white text-sm font-medium">
                  {getUserInitials()}
                </AvatarFallback>
              </Avatar>
              <div className="hidden md:flex flex-col items-start">
                <span className="text-sm font-medium text-gray-900">
                  {getUserDisplayName()}
                </span>
                <span className="text-xs text-gray-500 capitalize">
                  {user.role === 'facility_owner' ? 'Facility Owner' : 'Family Member'}
                </span>
              </div>
              <ChevronDown className="h-4 w-4 text-gray-500" />
            </Button>

            {isDropdownOpen && (
              <div className="absolute right-0 mt-2 w-56 bg-white border border-gray-200 rounded-md shadow-lg z-[100]">
                <div className="px-3 py-2 border-b">
                  <p className="text-sm font-medium">{getUserDisplayName()}</p>
                  <p className="text-xs text-gray-500">{user.email}</p>
                </div>

                <Link
                  href="/dashboard"
                  className="flex items-center px-3 py-2 text-sm text-gray-700 hover:bg-gray-100"
                  onClick={() => setIsDropdownOpen(false)}
                >
                  <User className="mr-2 h-4 w-4" />
                  My Account
                </Link>

                <Link
                  href="/favorites"
                  className="flex items-center px-3 py-2 text-sm text-gray-700 hover:bg-gray-100"
                  onClick={() => setIsDropdownOpen(false)}
                >
                  <Heart className="mr-2 h-4 w-4" />
                  Favorites
                </Link>

                {user.role === 'facility_owner' && (
                  <Link
                    href="/facility-owner/dashboard"
                    className="flex items-center px-3 py-2 text-sm text-gray-700 hover:bg-gray-100"
                    onClick={() => setIsDropdownOpen(false)}
                  >
                    <Settings className="mr-2 h-4 w-4" />
                    Owner Dashboard
                  </Link>
                )}

                {(user.role === 'admin' || user.role === 'super_admin') && (
                  <Link
                    href="/admin/dashboard"
                    className="flex items-center px-3 py-2 text-sm text-gray-700 hover:bg-gray-100"
                    onClick={() => setIsDropdownOpen(false)}
                  >
                    <Settings className="mr-2 h-4 w-4" />
                    Admin Panel
                  </Link>
                )}

                <hr className="my-1" />

                <button
                  className="flex items-center w-full px-3 py-2 text-sm text-red-600 hover:bg-gray-100"
                  onClick={() => {
                    setIsDropdownOpen(false)
                    handleLogout()
                  }}
                >
                  <LogOut className="mr-2 h-4 w-4" />
                  Sign Out
                </button>
              </div>
            )}
          </div>
        </div>
      )
    }

    // Not authenticated - show login/signup buttons
    return (
      <div className="flex items-center space-x-3">
        <Link href="/login">
          <Button
            variant="ghost"
            className="font-medium text-slate-700 hover:text-[#3F5CEA] hover:bg-[#3F5CEA]/5 transition-all duration-200"
          >
            Sign In
          </Button>
        </Link>
        <Link href="/register">
          <AnimatedButton
            className="font-medium bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white shadow-lg hover:shadow-xl hover:shadow-[#3F5CEA]/25 transition-all duration-300"
          >
            Get Started
          </AnimatedButton>
        </Link>
      </div>
    )
  }

  return (
    <motion.header
      className={cn(
        "sticky top-0 z-50 w-full transition-all duration-300",
        isScrolled
          ? "bg-white/95 backdrop-blur-md shadow-lg border-b border-slate-200/50"
          : "bg-white/90 backdrop-blur-sm border-b border-slate-100",
        className
      )}
      initial={{ y: -100 }}
      animate={{ y: 0 }}
      transition={{ type: "spring", stiffness: 300, damping: 30 }}
    >
      <div className="container mx-auto px-4 md:px-6">
        <div className="flex items-center justify-between h-16 md:h-20 lg:h-24">
          {/* Logo */}
          <motion.div
            className="flex items-center flex-shrink-0"
            whileHover={{ scale: 1.02 }}
            transition={{ type: "spring", stiffness: 400, damping: 25 }}
          >
            <Link href="/" className="flex items-center">
              <div className="relative">
                <Image
                  src="/images/geezer-guide-logo.png"
                  alt="Geezer Guide"
                  width={220}
                  height={110}
                  className="h-12 md:h-16 lg:h-20 xl:h-24 w-auto drop-shadow-sm"
                  priority
                />
              </div>
            </Link>
          </motion.div>

          {/* Desktop Navigation */}
          <nav className="hidden xl:flex items-center space-x-1">
            {navigationItems.map((item) => (
              <motion.div
                key={item.href}
                whileHover={{ y: -1 }}
                transition={{ type: "spring", stiffness: 400, damping: 25 }}
              >
                <Link
                  href={item.href}
                  className={cn(
                    "relative px-3 py-2 font-medium text-base transition-all duration-200 rounded-lg group whitespace-nowrap",
                    isActive(item.href)
                      ? "text-[#3F5CEA] bg-[#3F5CEA]/5"
                      : "text-slate-700 hover:text-[#3F5CEA] hover:bg-[#3F5CEA]/5"
                  )}
                >
                  {item.label}
                  <span
                    className={cn(
                      "absolute bottom-0 left-1/2 h-0.5 bg-[#3F5CEA] transition-all duration-300 transform -translate-x-1/2",
                      isActive(item.href)
                        ? "w-6"
                        : "w-0 group-hover:w-6"
                    )}
                  />
                </Link>
              </motion.div>
            ))}
          </nav>

          {/* Desktop Auth Buttons */}
          <div className="hidden xl:flex items-center space-x-3">
            {/* Advertise With Us CTA Button */}
            <Link href="/advertise">
              <Button
                className="bg-gradient-to-r from-[#3F5CEA] to-[#4A6CF7] hover:from-[#09183D] hover:to-[#3F5CEA] text-white font-semibold px-4 py-2 shadow-lg hover:shadow-xl transition-all text-sm whitespace-nowrap"
              >
                Advertise With Us
              </Button>
            </Link>

            {renderAuthSection()}
          </div>

          {/* Mobile Menu Button */}
          <div className="xl:hidden flex-shrink-0">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              className="p-2"
            >
              {isMobileMenuOpen ? (
                <X className="h-6 w-6" />
              ) : (
                <Menu className="h-6 w-6" />
              )}
            </Button>
          </div>
        </div>

        {/* Mobile Navigation */}
        <AnimatePresence>
          {isMobileMenuOpen && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.2 }}
              className="xl:hidden border-t border-slate-100 bg-white/95 backdrop-blur-md"
            >
              <div className="py-4 space-y-1">
                {navigationItems.map((item) => (
                  <Link
                    key={item.href}
                    href={item.href}
                    onClick={() => setIsMobileMenuOpen(false)}
                    className={cn(
                      "block px-4 py-2.5 font-medium text-base transition-colors rounded-lg",
                      isActive(item.href)
                        ? "text-[#3F5CEA] bg-[#3F5CEA]/10"
                        : "text-slate-700 hover:text-[#3F5CEA] hover:bg-[#3F5CEA]/5"
                    )}
                  >
                    {item.label}
                  </Link>
                ))}

                {/* Advertise With Us in Mobile Menu */}
                <Link
                  href="/advertise"
                  onClick={() => setIsMobileMenuOpen(false)}
                  className="block mx-4 mt-2"
                >
                  <Button className="w-full bg-gradient-to-r from-[#3F5CEA] to-[#4A6CF7] hover:from-[#09183D] hover:to-[#3F5CEA] text-white font-semibold">
                    Advertise With Us
                  </Button>
                </Link>

                <div className="pt-3 border-t border-slate-100 space-y-1">
                  {isAuthenticated && user ? (
                    <>
                      <div className="flex items-center px-4 py-2 space-x-3">
                        <Avatar className="h-8 w-8">
                          <AvatarImage
                            src={user.profilePicture || ''}
                            alt={getUserDisplayName()}
                          />
                          <AvatarFallback className="bg-blue-600 text-white text-sm font-medium">
                            {getUserInitials()}
                          </AvatarFallback>
                        </Avatar>
                        <div className="flex flex-col">
                          <span className="text-sm font-medium text-gray-900">
                            {getUserDisplayName()}
                          </span>
                          <span className="text-xs text-gray-500 capitalize">
                            {user.role === 'facility_owner' ? 'Facility Owner' : 'Family Member'}
                          </span>
                        </div>
                      </div>

                      <Link
                        href="/dashboard"
                        onClick={() => setIsMobileMenuOpen(false)}
                        className="block px-4 py-2.5 font-medium text-base text-slate-700 hover:text-[#3F5CEA] hover:bg-[#3F5CEA]/5 transition-colors rounded-lg"
                      >
                        My Account
                      </Link>

                      <Link
                        href="/favorites"
                        onClick={() => setIsMobileMenuOpen(false)}
                        className="block px-4 py-2.5 font-medium text-base text-slate-700 hover:text-[#3F5CEA] hover:bg-[#3F5CEA]/5 transition-colors rounded-lg"
                      >
                        Favorites
                      </Link>

                      {user.role === 'facility_owner' && (
                        <Link
                          href="/facility-owner/dashboard"
                          onClick={() => setIsMobileMenuOpen(false)}
                          className="block px-4 py-2.5 font-medium text-base text-slate-700 hover:text-[#3F5CEA] hover:bg-[#3F5CEA]/5 transition-colors rounded-lg"
                        >
                          Owner Dashboard
                        </Link>
                      )}

                      {(user.role === 'admin' || user.role === 'super_admin') && (
                        <Link
                          href="/admin/dashboard"
                          onClick={() => setIsMobileMenuOpen(false)}
                          className="block px-4 py-2.5 font-medium text-base text-slate-700 hover:text-[#3F5CEA] hover:bg-[#3F5CEA]/5 transition-colors rounded-lg"
                        >
                          Admin Panel
                        </Link>
                      )}

                      <button
                        onClick={() => {
                          handleLogout()
                          setIsMobileMenuOpen(false)
                        }}
                        className="block w-full text-left px-4 py-2.5 font-medium text-base text-red-600 hover:bg-red-50 transition-colors rounded-lg"
                      >
                        Sign Out
                      </button>
                    </>
                  ) : (
                    <>
                      <Link
                        href="/login"
                        onClick={() => setIsMobileMenuOpen(false)}
                        className="block px-4 py-2.5 font-medium text-base text-slate-700 hover:text-[#3F5CEA] hover:bg-[#3F5CEA]/5 transition-colors rounded-lg"
                      >
                        Sign In
                      </Link>
                      <Link
                        href="/register"
                        onClick={() => setIsMobileMenuOpen(false)}
                        className="block mx-4 mt-2"
                      >
                        <Button className="w-full bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white font-semibold">
                          Get Started
                        </Button>
                      </Link>
                    </>
                  )}
                </div>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </motion.header>
  )
}
