"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { User, Settings, LogOut, LayoutDashboard, PlusCircle } from "lucide-react";
import { useState, useEffect } from "react";
import Image from "next/image";
import { authClient } from "@/lib/auth-client";
import { toast } from "sonner";

interface NavbarProps {
  user?: {
    id: string;
    name: string | null;
    image: string | null;
    role: "GUIDE" | "EXPLORER";
  } | null;
}

export default function Navbar({ user }: NavbarProps) {
  const pathname = usePathname();
  const router = useRouter();
  const initials = user?.name?.charAt(0).toUpperCase() || "U";
  const [avatarUrl, setAvatarUrl] = useState<string | null>(null);

  // Handle sign out
  const handleSignOut = async () => {
    try {
      await authClient.signOut({
        fetchOptions: {
          onSuccess: () => {
            toast.success("Signed out successfully");
            router.push("/login");
            router.refresh();
          },
          onError: (ctx) => {
            toast.error(ctx.error.message ?? "Failed to sign out");
          },
        },
      });
    } catch (error) {
      console.error("Sign out error:", error);
      toast.error("Failed to sign out");
    }
  };

  // Fetch signed URL for avatar
  useEffect(() => {
    const userImage = user?.image;
    
    if (!userImage) return;

    // If it's a local path or full URL, use it directly
    if (userImage.startsWith('/') || userImage.startsWith('http')) {
      // Use setTimeout to avoid cascading effect
      const timer = setTimeout(() => setAvatarUrl(userImage), 0);
      return () => clearTimeout(timer);
    }

    // If it's an S3 key, fetch signed URL
    if (userImage.startsWith('avatars/')) {
      let isMounted = true;
      
      const fetchSignedUrl = async () => {
        try {
          const response = await fetch(
            `/api/images/signed-url?key=${encodeURIComponent(userImage)}`
          );
          
          if (response.ok && isMounted) {
            const data = await response.json();
            setAvatarUrl(data.url);
          }
        } catch (error) {
          console.error('Error fetching avatar signed URL:', error);
        }
      };

      fetchSignedUrl();

      return () => {
        isMounted = false;
      };
    }
  }, [user?.image]);

  // Hide navbar on auth pages (login, signup)
  const isAuthPage = pathname?.startsWith("/login") || pathname?.startsWith("/signup");

  if (isAuthPage) {
    return null;
  }

  return (
    <header className="border-b sticky top-0 bg-white z-50">
      <div className="container mx-auto px-4 py-4">
        <div className="flex items-center justify-between">
          <Link href="/" className="flex items-center gap-2">
            <Image
              src="/assets/ZuriGuide Logo.png"
              alt="ZuriGuide Logo"
              width={150}
              height={50}
              priority
              className="object-contain w-[200px] h-20"
            />
          </Link>

          <div className="flex items-center gap-3">
            {user ? (
              <>
                <Link href="/tours">
                  <Button variant="ghost">Browse Tours</Button>
                </Link>

                {user.role === "GUIDE" && (
                  <Link href="/tours/create">
                    <Button variant="outline">
                      <PlusCircle className="h-4 w-4 mr-2" />
                      Create Tour
                    </Button>
                  </Link>
                )}

                {/* User Avatar Dropdown */}
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" className="relative h-10 w-10 rounded-full">
                      <Avatar className="h-10 w-10">
                        {avatarUrl ? (
                          <Image 
                            src={avatarUrl} 
                            alt={user.name || "User"} 
                            width={40}
                            height={40}
                            quality={95}
                            priority
                            className="rounded-full object-cover"
                          />
                        ) : (
                          <AvatarFallback>{initials}</AvatarFallback>
                        )}
                      </Avatar>
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end" className="w-56">
                    <DropdownMenuLabel>
                      <div className="flex flex-col space-y-1">
                        <p className="text-sm font-medium leading-none">{user.name || "User"}</p>
                        <p className="text-xs leading-none text-muted-foreground">
                          {user.role}
                        </p>
                      </div>
                    </DropdownMenuLabel>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem asChild>
                      <Link href="/profile" className="cursor-pointer">
                        <User className="mr-2 h-4 w-4" />
                        <span>My Profile</span>
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuItem asChild>
                      <Link href="/dashboard" className="cursor-pointer">
                        <LayoutDashboard className="mr-2 h-4 w-4" />
                        <span>Dashboard</span>
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuItem asChild>
                      <Link href="/bookings" className="cursor-pointer">
                        <Settings className="mr-2 h-4 w-4" />
                        <span>My Bookings</span>
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem 
                      className="cursor-pointer text-red-600"
                      onClick={handleSignOut}
                    >
                      <LogOut className="mr-2 h-4 w-4" />
                      <span>Sign out</span>
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </>
            ) : (
              <>
                <Link href="/tours">
                  <Button variant="ghost">Browse Tours</Button>
                </Link>
                <Link href="/login">
                  <Button variant="ghost">Sign in</Button>
                </Link>
                <Link href="/signup">
                  <Button>Get started</Button>
                </Link>
              </>
            )}
          </div>
        </div>
      </div>
    </header>
  );
}
