"use client";
import { useState, useEffect, useRef } from "react";
import { User, ChevronDown } from "lucide-react";
import Link from "next/link";
import { useSession } from "next-auth/react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { usePathname } from "next/navigation";
import { signOut } from "next-auth/react";

const HeaderRight = () => {
  const { data: session, status } = useSession();
  const pathname = usePathname();
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsDropdownOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const toggleDropdown = () => {
    setIsDropdownOpen(!isDropdownOpen);
  };

  const handleLinkClick = () => {
    setIsDropdownOpen(false);
  };

  const logoutHandler = async () => {
    await signOut({
      redirectTo: "/auth/login",
      callbackUrl: "/auth/login",
    });
  };

  return (
    <>
      {status === "authenticated" ? (
        <div className="flex items-center">
          <div className="relative" ref={dropdownRef}>
            <div
              className="flex cursor-pointer items-center space-x-2 text-sm"
              onClick={toggleDropdown}
            >
              <Avatar className="h-7 w-7">
                <AvatarImage
                  src={session.user.image || ""}
                  alt={session.user.name || ""}
                />
                <AvatarFallback>
                  {session.user.name
                    ? session.user.name.charAt(0).toUpperCase()
                    : "U"}
                </AvatarFallback>
              </Avatar>
              <div className="flex items-center">
                <p className="hidden font-medium md:inline-block">
                  {session.user.name}
                </p>
                <ChevronDown className="ml-1 h-3 w-3" />
              </div>
            </div>

            {isDropdownOpen && (
              <div className="left:0 absolute right-auto z-50 mt-1 w-56 rounded-md border border-gray-200 bg-white shadow-lg md:left-auto md:right-0">
                <div className="rounded-t-md bg-blue-900 p-3 text-white">
                  <p className="font-medium">{session.user.name}</p>
                  <p className="text-xs text-blue-100">{session.user.email}</p>
                </div>

                <div className="py-1">
                  {session.user.role !== "USER" && (
                    <Link
                      href={
                        session.user.role === "ADMIN" ? "/admin" : "/moderator"
                      }
                      className="flex items-center px-4 py-2 text-sm text-gray-700 transition-colors hover:bg-blue-50"
                      onClick={handleLinkClick}
                    >
                      <svg
                        className="mr-2 h-4 w-4 text-indigo-600"
                        xmlns="http://www.w3.org/2000/svg"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      >
                        <rect x="3" y="3" width="7" height="9"></rect>
                        <rect x="14" y="3" width="7" height="5"></rect>
                        <rect x="14" y="12" width="7" height="9"></rect>
                        <rect x="3" y="16" width="7" height="5"></rect>
                      </svg>
                      Dashboard
                    </Link>
                  )}

                  <Link
                    href="/settings"
                    className="flex items-center px-4 py-2 text-sm text-gray-700 transition-colors hover:bg-blue-50"
                    onClick={handleLinkClick}
                  >
                    <svg
                      className="mr-2 h-4 w-4 text-gray-600"
                      xmlns="http://www.w3.org/2000/svg"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <circle cx="12" cy="12" r="3"></circle>
                      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                    </svg>
                    Settings
                  </Link>
                </div>

                <div className="border-t border-gray-100 py-1">
                  <div
                    className="flex !cursor-pointer items-center px-4 py-2 text-sm text-gray-700 transition-colors hover:bg-blue-50"
                    onClick={logoutHandler}
                  >
                    <svg
                      className="mr-2 h-4 w-4 text-red-500"
                      xmlns="http://www.w3.org/2000/svg"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                      <polyline points="16 17 21 12 16 7"></polyline>
                      <line x1="21" y1="12" x2="9" y2="12"></line>
                    </svg>
                    Sign Out
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      ) : (
        <div className="flex items-center space-x-2">
          <Link href="/auth/login">
            <Button
              variant="ghost"
              size="sm"
              className={`${
                pathname === "/login" ? "text-blue-500" : ""
              } hover:bg-blue-50 hover:text-blue-500`}
            >
              <User className="mr-1 h-3.5 w-3.5" />
              Login
            </Button>
          </Link>
          <Link href="/auth/register">
            <Button size="sm" className="bg-blue-900 hover:bg-blue-800">
              Sign Up
            </Button>
          </Link>
        </div>
      )}
    </>
  );
};

export default HeaderRight;
