"use client"

import { useState, useEffect, useRef } from "react"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet"
import {
  Cpu,
  Menu,
  Bell,
  X,
  User,
  Settings,
  LogOut,
  Wrench,
  Users,
  BookOpen,
  MessageSquare,
  BarChart3,
  Home,
  Heart,
  Eye,
  Plus,
  Search,
  LogIn,
  Shield,
  LayoutGrid,
} from "lucide-react"
import { useAuth } from "@/contexts/supabase-auth-context"
import { useLoading } from "@/contexts/loading-context"
import { supabase } from "@/lib/supabase"

interface NavigationProps {
  variant?: "default" | "minimal" | "dashboard"
}

export function Navigation({ variant = "default" }: NavigationProps) {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
  const { user, logout } = useAuth()
  const pathname = usePathname()
  const router = useRouter()
  const { startLoading, stopLoading } = useLoading()
  const [notifications, setNotifications] = useState<any[]>([])
  const [unreadCount, setUnreadCount] = useState(0)

  useEffect(() => {
    if (!user) return

    const fetchNotifications = async () => {
      const { data, error } = await supabase
        .from("notifications")
        .select(`
          notification_id,
          type,
          created_at,
          is_read,
          build_id,
          comment_id,
          actor:users!fk_notify_actor (
            user_id,
            user_name,
            avatar_url
          ),
          builds!fk_notify_build (
            build_name
          )
        `)
        .eq("user_id", user.user_id)
        .order("created_at", { ascending: false })
        .limit(10)

      if (!error && data) {
        setNotifications(data)
        setUnreadCount(data.filter(n => !n.is_read).length)
      }
    }

    fetchNotifications()
  }, [user])

  const NotificationsDropdown = () => {
    const { user } = useAuth()
    const [isSheetOpen, setIsSheetOpen] = useState(false)
    const [notifications, setNotifications] = useState<any[]>([])
    const [unreadCount, setUnreadCount] = useState(0)
    const [loadingMore, setLoadingMore] = useState(false)
    const [hasMore, setHasMore] = useState(true)
    const PAGE_SIZE = 10
    const containerRef = useRef<HTMLDivElement>(null)

    const formatTime = (dateString: string) => {
      const date = new Date(dateString)
      return new Intl.DateTimeFormat("en-US", {
        hour: "numeric",
        minute: "numeric",
        hour12: true,
      }).format(date)
    }

    const fetchNotifications = async (offset = 0) => {
      if (!user || !hasMore) return

      setLoadingMore(true)
      const { data, error } = await supabase
        .from("notifications")
        .select(`
          notification_id,
          type,
          created_at,
          is_read,
          build_id,
          comment_id,
          actor:users!fk_notify_actor (
            user_id,
            user_name,
            avatar_url
          ),
          builds!fk_notify_build (
            build_name
          )
        `)
        .eq("user_id", user.user_id)
        .order("created_at", { ascending: false })
        .range(offset, offset + PAGE_SIZE - 1)

      setLoadingMore(false)

      if (!error && data) {
        if (data.length < PAGE_SIZE) setHasMore(false)
        // append new batch
        setNotifications(prev => [...prev, ...data])
        setUnreadCount(data.filter(n => !n.is_read).length + (offset === 0 ? 0 : unreadCount))
      }
    }

    const handleScroll = () => {
      if (!containerRef.current || loadingMore || !hasMore) return
      const { scrollTop, scrollHeight, clientHeight } = containerRef.current
      if (scrollTop + clientHeight >= scrollHeight - 5) {
        fetchNotifications(notifications.length)
      }
    }

    // Reset when sheet opens
    useEffect(() => {
      if (!isSheetOpen) {
        // Reset everything when closing
        setNotifications([])
        setUnreadCount(0)
        setHasMore(true)
      } else if (isSheetOpen && notifications.length === 0) {
        // Load first batch when opening if empty
        fetchNotifications(0)
      }
    }, [isSheetOpen])


    const handleMarkAsRead = async (notifId: string) => {
      await supabase
        .from("notifications")
        .update({ is_read: true })
        .eq("notification_id", notifId)

      setNotifications(prev =>
        prev.map(n => (n.notification_id === notifId ? { ...n, is_read: true } : n))
      )
      setUnreadCount(notifications.filter(n => !n.is_read).length)
    }

    const markAllAsRead = async () => {
      const unreadIds = notifications.filter(n => !n.is_read).map(n => n.notification_id)
      if (unreadIds.length === 0) return

      await supabase
        .from("notifications")
        .update({ is_read: true })
        .in("notification_id", unreadIds)

      setNotifications(prev => prev.map(n => ({ ...n, is_read: true })))
      setUnreadCount(0)
    }

    const renderNotificationItem = (notif: any) => {
      const linkHref =
        notif.type === "comment" && notif.comment_id
          ? `/builds/${notif.build_id}#comment-${notif.comment_id}`
          : notif.type === "follow"
          ? `/profile/${notif.actor.user_id}`
          : notif.build_id
          ? `/builds/${notif.build_id}`
          : "#"

      return (
        <Link
          key={notif.notification_id}
          href={linkHref}
          onClick={async () => {
            await handleMarkAsRead(notif.notification_id)
            setIsSheetOpen(false)
          }}
          className={`flex gap-3 items-start cursor-pointer px-3 py-2 rounded-md transition-colors ${
            !notif.is_read
              ? "bg-blue-50 dark:bg-blue-900/30 font-medium"
              : "hover:bg-slate-100 dark:hover:bg-slate-800"
          }`}
        >
          <Avatar className="h-8 w-8">
            <AvatarImage src={notif.actor.avatar_url || "/placeholder.svg"} />
            <AvatarFallback>{notif.actor.user_name.charAt(0).toUpperCase()}</AvatarFallback>
          </Avatar>

          <div className="flex-1 text-sm">
            <p>
              <span className="font-medium">{notif.actor.user_name}</span>{" "}
              {notif.type === "like" && "liked your build"}
              {notif.type === "comment" && "commented on your build"}
              {notif.type === "follow" && "started following you"}
              {notif.builds?.build_name && <span className="font-medium"> {notif.builds.build_name}</span>}
            </p>
            <p className="text-xs text-slate-500">{formatTime(notif.created_at)}</p>
          </div>

          {notif.type === "like" && <Heart className="h-4 w-4 text-red-500 mt-1" />}
          {notif.type === "comment" && <MessageSquare className="h-4 w-4 text-blue-500 mt-1" />}
          {notif.type === "follow" && <Users className="h-4 w-4 text-green-500 mt-1" />}
        </Link>
      )
    }

    return (
      <>
        <Button
          variant="ghost"
          size="icon"
          className="relative"
          onClick={() => setIsSheetOpen(true)}
        >
          <Bell className="h-5 w-5" />
          {unreadCount > 0 && (
            <Badge
              variant="destructive"
              className="absolute -top-1 -right-1 h-5 min-w-[1.25rem] rounded-full px-1 text-xs flex items-center justify-center"
            >
              {unreadCount}
            </Badge>
          )}
        </Button>

        <Sheet
          open={isSheetOpen}
          onOpenChange={(open) => {
            setIsSheetOpen(open)
            if (!open) markAllAsRead()
          }}
        >
          <SheetTrigger />
          <SheetContent side="right" className="w-[350px] sm:w-[400px]">
            <SheetHeader>
              <SheetTitle>All Notifications</SheetTitle>
              <SheetDescription>Recent activity on your account</SheetDescription>
            </SheetHeader>

            <div
              ref={containerRef}
              onScroll={handleScroll}
              className="mt-4 max-h-[80vh] overflow-y-auto space-y-3 scrollbar-none custom-scrollbar"
            >
              {notifications.length === 0 ? (
                <p className="text-sm text-slate-500 text-center">No notifications</p>
              ) : (
                notifications.map(renderNotificationItem)
              )}
              {loadingMore && (
                <p className="text-center text-sm text-slate-500">Loading more...</p>
              )}
            </div>
          </SheetContent>
        </Sheet>
      </>
    )
  }


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

  const handleLinkClick = (href: string, label: string) => {
    if (pathname !== href) {
      startLoading(`Loading ${label.toLowerCase()}...`)
      // Navigation will be handled by Next.js Link component
      // Loading will be managed by LoadingProvider based on pathname change
    }
  }

  const mainNavItems = [
    { href: "/builder", label: "PC Builder", icon: Wrench },
    { href: "/builds", label: "Community Builds", icon: Users },
    { href: "/guides", label: "Build Guides", icon: BookOpen },
    { href: "/services", label: "Our Services", icon: LayoutGrid },
    { href: "/support", label: "Support", icon: MessageSquare },
  ]

  const userNavItems = [
    { href: "/dashboard", label: "Dashboard", icon: Home },
    { href: "/profile", label: "Profile", icon: User },
    { href: "/mybuilds", label: "My Builds", icon: Wrench },
    { href: "/likedbuilds", label: "Liked Builds", icon: Heart },
    { href: "/settings", label: "Settings", icon: Settings },
    ...(user?.user_type === 'admin' ? [{ href: "/admin", label: "Admin Dashboard", icon: Shield }] : []),
  ]

  const handleLogout = async () => {
    await logout()
    setIsMobileMenuOpen(false)
    router.push("/")
    router.refresh()
  }

  if (variant === "minimal") {
    return (
      <header className="border-b bg-white/80 backdrop-blur-sm dark:bg-slate-900/80">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <Link href="/" className="flex items-center gap-2">
              <Cpu className="h-8 w-8 text-blue-600" />
              <h1 className="text-2xl font-bold text-slate-900 dark:text-white">BuildMate</h1>
            </Link>
            <div className="flex items-center gap-2">
              {user ? (
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" className="relative h-8 w-8 rounded-full">
                      <Avatar className="h-8 w-8 hover:ring-2 hover:ring-blue-500 transition">
                        <Avatar>
                          <AvatarImage src={user.avatar_url || "/placeholder.svg"} />
                          <AvatarFallback>
                            {(user.user_name || user.email || "U").charAt(0).toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                      </Avatar>
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent className="w-56" align="end" forceMount>
                    <DropdownMenuLabel className="font-normal">
                      <div className="flex flex-col space-y-1">
                        <p className="text-sm font-medium leading-none">{user.user_name || user.email?.split('@')[0] || "User"}</p>
                        <p className="text-xs leading-none text-muted-foreground">{user.email}</p>
                      </div>
                    </DropdownMenuLabel>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem asChild>
                      <Link href="/dashboard" onClick={() => handleLinkClick("/dashboard", "Dashboard")}>
                        Dashboard
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuItem asChild>
                      <Link href="/profile" onClick={() => handleLinkClick("/profile", "Profile")}>
                        Profile
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuItem asChild>
                      <Link href="/settings" onClick={() => handleLinkClick("/settings", "Settings")}>
                        Settings
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={handleLogout}>
                      Log out
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              ) : (
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="outline">
                      <User className="mr-2 h-4 w-4" />
                      Account
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent className="w-48" align="end" forceMount>
                    <DropdownMenuItem asChild>
                      <Link href="/login" onClick={() => handleLinkClick("/login", "Login")}>
                        <LogIn className="mr-2 h-4 w-4" />
                        Login
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuItem asChild>
                      <Link href="/register" onClick={() => handleLinkClick("/register", "Sign Up")}>
                        <Plus className="mr-2 h-4 w-4" />
                        Sign Up
                      </Link>
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              )}
            </div>
          </div>
        </div>
      </header>
    )
  }

  // Default variant
  return (
    <header className="border-b bg-white/80 backdrop-blur-sm dark:bg-slate-900/80">
      <div className="container mx-auto px-4 py-4">
        <div className="flex items-center justify-between">
          <Link href="/" className="flex items-center gap-2">
            <Cpu className="h-8 w-8 text-blue-600" />
            <h1 className="text-2xl font-bold text-slate-900 dark:text-white">BuildMate</h1>
          </Link>
          
          {/* Desktop Navigation */}
          <nav className="hidden md:flex items-center gap-6">
            {mainNavItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                onClick={() => handleLinkClick(item.href, item.label)}
                className={`flex items-center gap-2 text-sm font-medium transition-colors hover:text-slate-900 dark:hover:text-white ${
                  isActive(item.href)
                    ? "text-slate-900 dark:text-white"
                    : "text-slate-600 dark:text-slate-300"
                }`}
              >
                <item.icon className="h-4 w-4" />
                {item.label}
              </Link>
            ))}
          </nav>

          <div className="flex items-center gap-2">
            {user ? (
              <div className="flex items-center gap-3">
                <Button variant="outline" size="sm" asChild>
                  <Link href="/builder" onClick={() => handleLinkClick("/builder", "PC Builder")}>
                    <Plus className="h-4 w-4 mr-2" />
                    New Build
                  </Link>
                </Button>
                <NotificationsDropdown />
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" className="relative h-8 w-8 rounded-full">
                      <Avatar className="h-8 w-8 hover:ring-2 hover:ring-blue-500 transition">
                        <AvatarImage src={user.avatar_url || "/placeholder.svg"} />
                        <AvatarFallback>
                          {(user.user_name || user.email || "U").charAt(0).toUpperCase()}
                        </AvatarFallback>
                      </Avatar>
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent className="w-56" align="end" forceMount>
                    <DropdownMenuLabel className="font-normal">
                      <div className="flex flex-col space-y-1">
                        <p className="text-sm font-medium leading-none">{user.user_name || user.email?.split('@')[0] || "User"}</p>
                        <p className="text-xs leading-none text-muted-foreground">{user.email}</p>
                      </div>
                    </DropdownMenuLabel>
                    <DropdownMenuSeparator />
                    {userNavItems.map((item) => (
                      <DropdownMenuItem key={item.href} asChild>
                        <Link href={item.href} onClick={() => handleLinkClick(item.href, item.label)}>
                          <item.icon className="mr-2 h-4 w-4" />
                          {item.label}
                        </Link>
                      </DropdownMenuItem>
                    ))}
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={handleLogout}>
                      Log out
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            ) : (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline">
                    <User className="mr-2 h-4 w-4" />
                    Account
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="w-48" align="end" forceMount>
                  <DropdownMenuItem asChild>
                    <Link href="/login" onClick={() => handleLinkClick("/login", "Login")}>
                      <LogIn className="mr-2 h-4 w-4" />
                      Login
                    </Link>
                  </DropdownMenuItem>
                  <DropdownMenuItem asChild>
                    <Link href="/register" onClick={() => handleLinkClick("/register", "Sign Up")}>
                      <Plus className="mr-2 h-4 w-4" />
                      Sign Up
                    </Link>
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            )}

            {/* Mobile Menu */}
            <Sheet open={isMobileMenuOpen} onOpenChange={setIsMobileMenuOpen}>
              <SheetTrigger asChild>
                <Button variant="ghost" size="sm" className="md:hidden">
                  <Menu className="h-5 w-5" />
                </Button>
              </SheetTrigger>
              <SheetContent side="right" className="w-[300px] sm:w-[400px]">
                <SheetHeader>
                  <SheetTitle className="flex items-center gap-2">
                    <Cpu className="h-6 w-6 text-blue-600" />
                    BuildMate
                  </SheetTitle>
                  <SheetDescription>
                    Navigate through the application
                  </SheetDescription>
                </SheetHeader>
                <div className="mt-6 space-y-4">
                  {/* Main Navigation */}
                  <div className="space-y-2">
                    <h3 className="text-sm font-medium text-slate-500 dark:text-slate-400">Main Menu</h3>
                    {mainNavItems.map((item) => (
                      <Link
                        key={item.href}
                        href={item.href}
                        className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                          isActive(item.href)
                            ? "bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-300"
                            : "text-slate-700 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"
                        }`}
                        onClick={() => {
                          handleLinkClick(item.href, item.label)
                          setIsMobileMenuOpen(false)
                        }}
                      >
                        {item.label}
                      </Link>
                    ))}
                  </div>

                  {/* User Navigation */}
                  {user && (
                    <div className="space-y-2">
                      <h3 className="text-sm font-medium text-slate-500 dark:text-slate-400">Account</h3>
                      {userNavItems.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                            isActive(item.href)
                              ? "bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-300"
                              : "text-slate-700 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"
                          }`}
                          onClick={() => {
                            handleLinkClick(item.href, item.label)
                            setIsMobileMenuOpen(false)
                          }}
                        >
                          {item.label}
                        </Link>
                      ))}
                      <button
                        onClick={handleLogout}
                        className="px-3 py-2 rounded-lg text-sm font-medium text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20 w-full text-left"
                      >
                        Log out
                      </button>
                    </div>
                  )}

                  {/* Guest Navigation */}
                  {!user && (
                    <div className="space-y-2">
                      <h3 className="text-sm font-medium text-slate-500 dark:text-slate-400">Account</h3>
                      <Link
                        href="/login"
                        className="px-3 py-2 rounded-lg text-sm font-medium text-slate-700 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"
                        onClick={() => setIsMobileMenuOpen(false)}
                      >
                        Login
                      </Link>
                      <Link
                        href="/register"
                        className="px-3 py-2 rounded-lg text-sm font-medium text-slate-700 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"
                        onClick={() => setIsMobileMenuOpen(false)}
                      >
                        Sign Up
                      </Link>
                    </div>
                  )}
                </div>
              </SheetContent>
            </Sheet>
          </div>
        </div>
      </div>
    </header>
  )
}
