"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Building2, ChevronDown, Clock, LogOut, Mail, Shield, User } from "lucide-react";
import { useAuthStore } from "@/stores";

export function BrapiUserMenu() {
  const router = useRouter();
  const user = useAuthStore((state) => state.user);
  const logout = useAuthStore((state) => state.logout);
  const [extras, setExtras] = useState<{ institute?: string; role?: string }>({});
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      const raw = localStorage.getItem("user_profile_extras");
      if (!raw) return;
      const parsed = JSON.parse(raw) as { institute?: string; role?: string };
      setExtras(parsed || {});
    } catch {}
  }, []);

  useEffect(() => {
    const handler = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const initials = useMemo(() => {
    const source = user?.name?.trim() || user?.account?.trim() || "User";
    return source
      .split(/\s+/)
      .map((part) => part[0])
      .join("")
      .slice(0, 2)
      .toUpperCase();
  }, [user?.account, user?.name]);

  const loginTime = useMemo(() => {
    const now = new Date();
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")} ${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
  }, []);

  const handleLogout = () => {
    setOpen(false);
    logout();
    router.replace("/login");
  };

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((value) => !value)}
        className="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-2 py-1.5 transition hover:bg-slate-50 dark:border-slate-800 dark:bg-slate-900 dark:hover:bg-slate-800"
      >
        <div className="grid h-7 w-7 place-items-center rounded-full bg-gradient-to-br from-green-500 to-emerald-600 text-xs font-semibold text-white">
          {initials}
        </div>
        <span className="max-w-[88px] truncate text-xs text-slate-700 dark:text-slate-200">{user?.name || user?.account || "未登录"}</span>
        <ChevronDown className={`h-3.5 w-3.5 text-slate-400 transition-transform ${open ? "rotate-180" : ""}`} />
      </button>

      {open ? (
        <div className="absolute right-0 top-full z-50 mt-2 w-72 overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-[0_8px_40px_rgba(0,0,0,0.14),0_2px_8px_rgba(0,0,0,0.08)] dark:border-slate-800 dark:bg-slate-900 dark:shadow-[0_8px_40px_rgba(0,0,0,0.4)]">
          <div className="bg-gradient-to-br from-green-500 to-emerald-600 px-5 py-4">
            <div className="flex items-center gap-3">
              <div className="grid h-12 w-12 place-items-center rounded-full bg-white/25 text-lg font-semibold text-white">{initials}</div>
              <div className="overflow-hidden">
                <p className="truncate text-white">{user?.name || user?.account || "未登录用户"}</p>
                <p className="mt-0.5 truncate text-xs text-green-100/80">{user?.email || "-"}</p>
              </div>
            </div>
          </div>

          <div className="space-y-2.5 border-b border-slate-100 px-4 py-3 dark:border-slate-800">
            <InfoRow icon={Shield} label="账号" value={user?.account || "-"} />
            <InfoRow icon={User} label="角色" value={extras.role || "试验管理员"} />
            <InfoRow icon={Building2} label="机构" value={extras.institute || "-"} />
            <InfoRow icon={Mail} label="邮箱" value={user?.email || "-"} />
            <InfoRow icon={Clock} label="本次登录" value={loginTime} />
          </div>

          <div className="border-t border-slate-100 px-3 pb-3 pt-2 dark:border-slate-800">
            <button
              type="button"
              onClick={handleLogout}
              className="flex w-full items-center gap-2.5 rounded-xl px-3 py-2 text-sm text-red-500 transition-colors hover:bg-red-50 dark:hover:bg-red-500/10"
            >
              <LogOut className="h-4 w-4" />
              <span>退出登录</span>
            </button>
          </div>
        </div>
      ) : null}
    </div>
  );
}

function InfoRow({
  icon: Icon,
  label,
  value,
}: {
  icon: React.ElementType;
  label: string;
  value: string;
}) {
  return (
    <div className="flex items-center gap-2.5">
      <Icon className="h-3.5 w-3.5 shrink-0 text-slate-400 dark:text-slate-500" />
      <span className="w-16 shrink-0 text-xs text-slate-400 dark:text-slate-500">{label}</span>
      <span className="truncate text-xs text-slate-700 dark:text-slate-200">{value}</span>
    </div>
  );
}
