"use client";

import { AnimatePresence, motion } from "motion/react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useAuth } from "@/app/components/providers/auth-provider";
import { DEFAULT_UNAUTHENTICATED_ROUTE } from "@/lib/auth/constants";
import { clearAuthToken } from "@/lib/auth/token";
import { logoutRequest } from "@/lib/api/auth";
import { IconLogout } from "../icons/nav-icons";

const dropdownMotion = {
  initial: { opacity: 0, y: -8, scale: 0.95 },
  animate: { opacity: 1, y: 0, scale: 1 },
  exit: { opacity: 0, y: -8, scale: 0.95 },
  transition: { duration: 0.2, ease: [0.16, 1, 0.3, 1] as const },
};

export function ProfileDropdown() {
  const router = useRouter();
  const { user, roleLabel, clearUser } = useAuth();
  const [open, setOpen] = useState(false);
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  const displayName = user?.fullName || "Pengguna";

  useEffect(() => {
    if (!open) return;

    function handleClickOutside(event: MouseEvent) {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target as Node)
      ) {
        setOpen(false);
      }
    }

    function handleEscape(event: KeyboardEvent) {
      if (event.key === "Escape") {
        setOpen(false);
      }
    }

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

  async function handleLogout() {
    if (isLoggingOut) return;

    setIsLoggingOut(true);
    setOpen(false);

    try {
      await logoutRequest();
    } catch {
      // Tetap bersihkan sesi lokal meskipun request logout gagal
    } finally {
      clearAuthToken();
      clearUser();
      setIsLoggingOut(false);
      router.push(DEFAULT_UNAUTHENTICATED_ROUTE);
      router.refresh();
    }
  }

  return (
    <div ref={containerRef} className="relative">
      <button
        type="button"
        onClick={() => setOpen((prev) => !prev)}
        className="flex cursor-pointer items-center gap-2 text-right transition-opacity hover:opacity-80"
        aria-label="Profil pengguna"
        aria-expanded={open}
        aria-haspopup="menu"
      >
        <div className="flex flex-col items-end">
          <span className="text-m-medium text-neutral-100">{displayName}</span>
          <span className="text-s-regular text-neutral-80">{roleLabel}</span>
        </div>
        <motion.div
          animate={{ scale: open ? 1.05 : 1 }}
          transition={{ duration: 0.2 }}
          className="size-9 shrink-0 overflow-hidden rounded-full"
        >
          <Image
            src="/images/avatar.png"
            alt={displayName}
            width={36}
            height={36}
            className="size-full object-cover"
          />
        </motion.div>
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            role="menu"
            className="absolute top-[calc(100%+8px)] right-0 z-50 w-[240px] origin-top-right rounded-[10px] border border-neutral-40 bg-neutral-10 p-2 shadow-sm"
            initial={dropdownMotion.initial}
            animate={dropdownMotion.animate}
            exit={dropdownMotion.exit}
            transition={dropdownMotion.transition}
          >
            <div className="flex h-[61px] items-center gap-2 rounded-lg border border-neutral-40 bg-neutral-10 px-4 py-2">
              <div className="flex min-w-0 flex-1 flex-col items-end">
                <span className="text-m-medium w-full truncate text-neutral-100">
                  {displayName}
                </span>
                <span className="text-m-light w-full truncate text-neutral-80">
                  {roleLabel}
                </span>
              </div>
              <Image
                src="/images/avatar.png"
                alt={displayName}
                width={36}
                height={36}
                className="size-9 shrink-0 rounded-full object-cover"
              />
            </div>

            <button
              type="button"
              role="menuitem"
              onClick={handleLogout}
              disabled={isLoggingOut}
              className="text-m-regular mt-2 flex h-[38px] w-full items-center gap-3 rounded-lg p-3 text-neutral-100 transition-colors duration-150 hover:bg-neutral-20 disabled:opacity-60"
            >
              <IconLogout className="shrink-0 text-neutral-100" />
              <span>{isLoggingOut ? "Keluar..." : "Keluar"}</span>
            </button>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
