"use client"

import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import { Search, HeartPulse, Menu, User, LogOut, ChevronDown } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { CrisisSupport } from "@/components/crisis-support"
import { Sheet, SheetContent, SheetTrigger, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { useState, useEffect } from "react"
import { cn } from "@/lib/utils"
import { fetchApi } from "@/lib/api-client"
import { useAuth } from "@/components/auth-provider"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

const NAV_LINKS = [
  { name: "Home", href: "/" },
  { name: "Q&A Forum", href: "/forum" },
  { name: "Expert Insights", href: "/insights" },
  { name: "Clinical Trials", href: "/trials" },
  { name: "News", href: "/news" },
  { name: "Guides", href: "/guides" },
]

export function Navbar() {
  const pathname = usePathname()
  const [isSearchOpen, setIsSearchOpen] = useState(false)
  const { user, logout } = useAuth()
  const [navLinks, setNavLinks] = useState(NAV_LINKS)

  useEffect(() => {
    fetchApi('content.php?page=navigation').then(data => {
      if (data.main?.links) {
        setNavLinks(JSON.parse(data.main.links))
      }
    }).catch(console.error)
  }, [])

  const handleSignOut = async () => {
    try {
      await fetchApi('auth.php?action=logout', { method: 'POST' });
    } catch (error) {
      console.error('Logout failed:', error);
    }
    logout()
  }

  return (
    <header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
      <div className="container mx-auto px-4">
        <div className="flex h-16 items-center justify-between gap-4">
          {/* Mobile Menu */}
          <div className="lg:hidden">
            <Sheet>
              <SheetTrigger asChild>
                <Button variant="ghost" size="icon">
                  <Menu className="h-6 w-6" />
                </Button>
              </SheetTrigger>
              <SheetContent side="left" className="w-[300px] sm:w-[400px]">
                <SheetHeader>
                  <SheetTitle className="flex items-center gap-2">
                    <HeartPulse className="h-6 w-6 text-primary" />
                    OncoConnect
                  </SheetTitle>
                </SheetHeader>
                <nav className="flex flex-col gap-4 mt-8">
                  {navLinks.map((link: any) => (
                    <Link
                      key={link.href}
                      href={link.href}
                      className={cn(
                        "text-lg font-medium transition-colors hover:text-primary",
                        pathname === link.href ? "text-primary" : "text-muted-foreground",
                      )}
                    >
                      {link.name}
                    </Link>
                  ))}
                  <hr className="my-2" />
                  <Link href="/login" className="text-lg font-medium hover:text-primary">
                    Login
                  </Link>
                  <Link href="/register" className="text-lg font-medium hover:text-primary">
                    Register
                  </Link>
                </nav>
              </SheetContent>
            </Sheet>
          </div>

          <Link href="/" className="flex items-center gap-2 shrink-0">
            <HeartPulse className="h-8 w-8 text-primary" />
            <span className="text-xl font-bold tracking-tight text-primary hidden sm:inline-block">OncoConnect</span>
          </Link>

          <nav className="hidden lg:flex items-center gap-6 text-sm font-medium">
            {navLinks.filter((l: any) => ["/", "/forum"].includes(l.href)).map((link: any) => (
              <Link
                key={link.href}
                href={link.href}
                className={cn(
                  "transition-colors hover:text-primary shrink-0",
                  pathname === link.href ? "text-primary" : "text-muted-foreground",
                )}
              >
                {link.name}
              </Link>
            ))}
            
            <DropdownMenu>
              <DropdownMenuTrigger className={cn(
                "flex items-center gap-1 transition-colors hover:text-primary outline-none shrink-0",
                navLinks.filter((l: any) => !["/", "/forum"].includes(l.href)).some((l: any) => pathname === l.href) 
                  ? "text-primary" 
                  : "text-muted-foreground"
              )}>
                Resources <ChevronDown className="h-4 w-4" />
              </DropdownMenuTrigger>
              <DropdownMenuContent align="start" className="w-48">
                {navLinks.filter((l: any) => !["/", "/forum"].includes(l.href)).map((link: any) => (
                  <DropdownMenuItem key={link.href} asChild>
                    <Link 
                      href={link.href}
                      className={cn(
                        "w-full cursor-pointer",
                        pathname === link.href ? "text-primary font-bold" : ""
                      )}
                    >
                      {link.name}
                    </Link>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
          </nav>

          <div className="flex flex-1 items-center justify-end gap-2 sm:gap-4">
            <div className="relative hidden md:block w-full max-w-sm lg:max-w-md xl:max-w-lg transition-all">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                type="search"
                placeholder="Search resources, articles, guides..."
                className="pl-8 bg-muted/50 border-none focus-visible:ring-1 focus-visible:ring-primary/20 h-9 w-full"
              />
            </div>

            <div className="flex items-center gap-2">
              <CrisisSupport />
              <div className="hidden sm:flex items-center gap-2 border-l pl-4 ml-2">
                {user ? (
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="rounded-full bg-primary/10">
                        <User className="h-5 w-5 text-primary" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="w-56">
                      <DropdownMenuLabel>My Account</DropdownMenuLabel>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem asChild>
                        <Link href="/profile">Profile</Link>
                      </DropdownMenuItem>
                      <DropdownMenuItem asChild>
                        <Link href="/insights/create">Create Article</Link>
                      </DropdownMenuItem>
                      {(user.role === 'admin' || user.role === 'moderator') && (
                        <DropdownMenuItem asChild>
                          <Link href="/orchard-v3-panel" className="text-primary font-medium">System Management</Link>
                        </DropdownMenuItem>
                      )}
                      <DropdownMenuSeparator />
                      <DropdownMenuItem onClick={handleSignOut} className="text-destructive">
                        <LogOut className="mr-2 h-4 w-4" />
                        Log out
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                ) : (
                  <>
                    <Button variant="ghost" size="sm" asChild>
                      <Link href="/login">Log in</Link>
                    </Button>
                    <Button size="sm" asChild className="rounded-full shadow-md">
                      <Link href="/register">Sign up</Link>
                    </Button>
                  </>
                )}
              </div>
              <Button variant="ghost" size="icon" className="sm:hidden" onClick={() => setIsSearchOpen(!isSearchOpen)}>
                <Search className="h-5 w-5" />
              </Button>
            </div>
          </div>
        </div>
      </div>
      {/* Mobile Search Overlay */}
      {isSearchOpen && (
        <div className="lg:hidden px-4 py-2 border-t bg-background">
          <div className="relative">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
            <Input type="search" placeholder="Search..." className="pl-8 bg-muted/50 border-none h-9" autoFocus />
          </div>
        </div>
      )}
    </header>
  )
}
