import { Link, useNavigate } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import { Bell, ChevronDown, LifeBuoy, LogOut, Settings, User, X } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useAccount, userInitials, timeAgo } from "@/lib/account-store";

function useDismiss(open: boolean, close: () => void) {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!open) return;
    function onClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) close();
    }
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") close();
    }
    document.addEventListener("mousedown", onClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open, close]);
  return ref;
}

const menuItem =
  "flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-ink transition-colors hover:bg-[#f6f6f7]";

export function AccountMenu() {
  const { profile, notifications, unreadCount, markAllRead, markRead, dismiss } = useAccount();
  const navigate = useNavigate();
  const qc = useQueryClient();

  const [bellOpen, setBellOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [signOutOpen, setSignOutOpen] = useState(false);
  const [tab, setTab] = useState<"all" | "unread">("all");

  const bellRef = useDismiss(bellOpen, () => setBellOpen(false));
  const menuRef = useDismiss(menuOpen, () => setMenuOpen(false));

  const list = tab === "unread" ? notifications.filter((n) => !n.read) : notifications;

  async function signOut() {
    await qc.cancelQueries();
    qc.clear();
    await supabase.auth.signOut();
    navigate({ to: "/partners", replace: true });
  }

  return (
    <div className="flex items-center gap-1.5">
      <div className="relative" ref={bellRef}>
        <button
          type="button"
          aria-label="Notifications"
          onClick={() => {
            setBellOpen((v) => !v);
            setMenuOpen(false);
          }}
          className="relative inline-flex h-9 w-9 items-center justify-center rounded-full text-ink-2 transition-colors hover:bg-[#f2f2f3] hover:text-ink"
        >
          <Bell className="h-[18px] w-[18px]" />
          {unreadCount > 0 && (
            <span className="absolute -right-0.5 -top-0.5 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-[#FF4308] px-1 text-[10px] font-bold text-white">
              {unreadCount}
            </span>
          )}
        </button>

        {bellOpen && (
          <div className="absolute right-0 z-50 mt-2 w-[min(92vw,380px)] overflow-hidden rounded-2xl border border-hairline bg-white shadow-xl">
            <div className="flex items-center justify-between border-b border-hairline px-4 py-3">
              <span className="text-sm font-bold text-ink">Notifications</span>
              <button
                type="button"
                onClick={markAllRead}
                className="text-xs font-semibold text-[#FF4308]"
              >
                Mark all as read
              </button>
            </div>
            <div className="flex gap-1 border-b border-hairline px-3 py-2">
              {(["all", "unread"] as const).map((t) => (
                <button
                  key={t}
                  type="button"
                  onClick={() => setTab(t)}
                  className={`rounded-lg px-3 py-1.5 text-xs font-semibold capitalize ${
                    tab === t ? "bg-[#FF4308]/10 text-[#FF4308]" : "text-ink-2 hover:bg-[#f6f6f7]"
                  }`}
                >
                  {t}
                </button>
              ))}
            </div>
            <div className="max-h-[320px] overflow-y-auto">
              {list.length === 0 && (
                <p className="px-4 py-10 text-center text-sm text-ink-2">You're all caught up.</p>
              )}
              {list.map((n) => (
                <div
                  key={n.id}
                  className={`group flex gap-3 border-b border-hairline px-4 py-3 last:border-0 ${
                    n.read ? "bg-white" : "bg-[#FF4308]/[0.04]"
                  }`}
                >
                  <span
                    className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${n.read ? "bg-transparent" : "bg-[#FF4308]"}`}
                  />
                  <div className="min-w-0 flex-1">
                    <p className="text-[11px] font-semibold uppercase tracking-wide text-ink-3">
                      {n.category}
                    </p>
                    <button
                      type="button"
                      onClick={() => {
                        markRead(n.id);
                        setBellOpen(false);
                        if (n.href) navigate({ to: n.href });
                      }}
                      className="block text-left text-sm font-semibold text-ink hover:text-[#FF4308]"
                    >
                      {n.title}
                    </button>
                    <p className="text-sm text-ink-2">{n.body}</p>
                    <p className="mt-1 text-xs text-ink-3">{timeAgo(n.createdAt)}</p>
                  </div>
                  <button
                    type="button"
                    aria-label="Dismiss notification"
                    onClick={() => dismiss(n.id)}
                    className="h-6 w-6 shrink-0 rounded-md text-ink-3 opacity-0 transition-opacity hover:bg-[#f2f2f3] group-hover:opacity-100"
                  >
                    <X className="mx-auto h-3.5 w-3.5" />
                  </button>
                </div>
              ))}
            </div>
            <Link
              to="/notifications"
              onClick={() => setBellOpen(false)}
              className="block border-t border-hairline px-4 py-3 text-center text-sm font-semibold text-[#FF4308]"
            >
              View all notifications
            </Link>
          </div>
        )}
      </div>

      <div className="relative" ref={menuRef}>
        <button
          type="button"
          onClick={() => {
            setMenuOpen((v) => !v);
            setBellOpen(false);
          }}
          aria-haspopup="menu"
          aria-expanded={menuOpen}
          className="flex items-center gap-2 rounded-full py-1 pl-1 pr-2 transition-colors hover:bg-[#f2f2f3]"
        >
          <span className="inline-flex h-8 w-8 items-center justify-center rounded-full bg-[#0a0a12] text-xs font-bold text-white">
            {userInitials(profile)}
          </span>
          <span className="hidden text-sm font-semibold text-ink sm:block">
            {profile.firstName} {profile.lastName}
          </span>
          <ChevronDown className="h-4 w-4 text-ink-3" />
        </button>

        {menuOpen && (
          <div
            role="menu"
            className="absolute right-0 z-50 mt-2 w-[min(92vw,264px)] rounded-2xl border border-hairline bg-white p-1.5 shadow-xl"
          >
            <div className="px-3 py-2">
              <p className="truncate text-sm font-bold text-ink">
                {profile.firstName} {profile.lastName}
              </p>
              <p className="truncate text-xs text-ink-2">{profile.email}</p>
            </div>
            <div className="my-1 h-px bg-hairline" />
            <Link to="/profile" onClick={() => setMenuOpen(false)} className={menuItem}>
              <User className="h-4 w-4 text-ink-3" /> My Profile
            </Link>
            <Link to="/notifications" onClick={() => setMenuOpen(false)} className={menuItem}>
              <Bell className="h-4 w-4 text-ink-3" /> Notifications
            </Link>
            <Link to="/settings" onClick={() => setMenuOpen(false)} className={menuItem}>
              <Settings className="h-4 w-4 text-ink-3" /> Settings
            </Link>
            <div
              role="menuitem"
              aria-disabled="true"
              className="flex w-full cursor-not-allowed items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-ink-4"
            >
              <LifeBuoy className="h-4 w-4" /> Help & Support
            </div>
            <div className="my-1 h-px bg-hairline" />
            <button
              type="button"
              onClick={() => {
                setMenuOpen(false);
                setSignOutOpen(true);
              }}
              className={`${menuItem} text-rose-600`}
            >
              <LogOut className="h-4 w-4" /> Sign Out
            </button>
          </div>
        )}
      </div>

      {signOutOpen && (
        <div
          className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4"
          onClick={() => setSignOutOpen(false)}
        >
          <div
            className="w-full max-w-sm rounded-2xl border border-hairline bg-white p-6"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="text-base font-bold text-ink">Sign out?</h2>
            <p className="mt-2 text-sm text-ink-2">Are you sure you want to sign out?</p>
            <div className="mt-6 flex justify-end gap-2">
              <button
                type="button"
                onClick={() => setSignOutOpen(false)}
                className="btn-ghost text-sm"
              >
                Cancel
              </button>
              <button type="button" onClick={signOut} className="btn-brand text-sm">
                Sign Out
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
