"use client";

import { useState, useMemo, useRef, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Search, LogOut, Navigation, HelpCircle } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import Modal from "@/components/ui/Modal";
import Button from "@/components/ui/Button";

type TopbarProps = {
  name: string;
  email: string;
  role?: "admin" | "volunteer";
  profileHref?: string;
  /** Initial avatar URL, e.g. server-fetched from the layout. Optional —
   * the component also fetches the latest value itself on mount so it
   * stays correct even if this prop is stale. */
  avatarUrl?: string | null;
};

type NavItem = {
  label: string;
  href: string;
  keywords: string[];
};

// Custom event name used to broadcast avatar changes across the app without
// needing a global state manager. The Profile page dispatches this right
// after a successful save; Topbar listens and updates instantly.
export const AVATAR_UPDATED_EVENT = "profile-avatar-updated";

export default function Topbar({
  name,
  email,
  role = "volunteer",
  profileHref = "/profile",
  avatarUrl: avatarUrlProp = null,
}: TopbarProps) {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const [showConfirm, setShowConfirm] = useState(false);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string | null>(avatarUrlProp);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const initials = name
    .split(" ")
    .map((n) => n[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();

  // Fetch the freshest avatar on mount, in case the server-rendered prop is
  // stale (e.g. cached layout from before the user's last save).
  useEffect(() => {
    const supabase = createClient();
    (async () => {
      const { data: userRes } = await supabase.auth.getUser();
      if (!userRes.user) return;
      const { data } = await supabase
        .from("profiles")
        .select("avatar_url")
        .eq("id", userRes.user.id)
        .single();
      if (data) setAvatarUrl(data.avatar_url ?? null);
    })();
  }, []);

  // Live-update the moment the Profile page saves a new picture — no
  // navigation, no logout/login, no manual refresh needed.
  useEffect(() => {
    function handleAvatarUpdate(e: Event) {
      const detail = (e as CustomEvent<{ avatarUrl: string | null }>).detail;
      setAvatarUrl(detail?.avatarUrl ?? null);
    }
    window.addEventListener(AVATAR_UPDATED_EVENT, handleAvatarUpdate);
    return () => window.removeEventListener(AVATAR_UPDATED_EVENT, handleAvatarUpdate);
  }, []);

  // Navigation pages list for search suggestions
  const navList = useMemo(() => {
    const adminPages: NavItem[] = [
      { label: "Dashboard Overview", href: "/", keywords: ["home", "dashboard", "main", "overview", "stats"] },
      { label: "Manage Volunteer Programs", href: "/programs", keywords: ["programs", "events", "activities", "calendar"] },
      { label: "Manage Volunteers List", href: "/volunteers", keywords: ["volunteers", "students", "members", "skills"] },
      { label: "Approve Applications", href: "/applications", keywords: ["applications", "pending", "approvals", "pdf"] },
      { label: "Merit & Awards Panel", href: "/merit", keywords: ["merit", "points", "rewards", "leaderboard", "badge"] },
      { label: "Issue Certificates", href: "/certificates", keywords: ["certificates", "issue", "generate", "pdf"] },
      { label: "Organize Reminders", href: "/reminders", keywords: ["reminders", "telegram", "notifications"] },
      { label: "Review Program Feedbacks", href: "/feedback", keywords: ["feedback", "reviews", "ratings", "stars"] },
      { label: "My Profile Settings", href: "/profile", keywords: ["profile", "settings", "avatar", "password"] },
    ];

    const volunteerPages: NavItem[] = [
      { label: "Student Dashboard", href: "/", keywords: ["home", "dashboard", "main", "overview", "merit"] },
      { label: "Browse Open Programs", href: "/programs", keywords: ["programs", "events", "activities", "apply", "calendar"] },
      { label: "My Application Statuses", href: "/applications", keywords: ["applications", "activity", "pending", "history"] },
      { label: "My Merit Points Statement", href: "/merit", keywords: ["merit", "points", "transactions", "ledger"] },
      { label: "My Achievements & Badges", href: "/achievement", keywords: ["achievements", "badges", "rewards", "bronze", "silver", "gold"] },
      { label: "My Earned Certificates", href: "/certificates", keywords: ["certificates", "download", "pdf", "appreciation"] },
      { label: "My Inbox", href: "/inbox", keywords: ["inbox", "notifications", "announcements", "reminders"] },
      { label: "Submit Program Feedback", href: "/feedback", keywords: ["feedback", "reviews", "stars", "rating"] },
      { label: "My Profile & Skill Tags", href: "/profile", keywords: ["profile", "settings", "avatar", "skills"] },
    ];

    return role === "admin" ? adminPages : volunteerPages;
  }, [role]);

  // Filtered suggestions based on search query
  const suggestions = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return [];
    return navList.filter(
      (item) =>
        item.label.toLowerCase().includes(q) ||
        item.keywords.some((kw) => kw.includes(q))
    );
  }, [query, navList]);

  // Close suggestions dropdown on outside click
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowSuggestions(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  async function signOut() {
    const supabase = createClient();
    await supabase.auth.signOut();
    setShowConfirm(false);
    router.push("/login");
    router.refresh();
  }

  function handleNavigate(href: string) {
    router.push(href);
    setQuery("");
    setShowSuggestions(false);
  }

  return (
    <div className="relative flex items-center gap-4 z-30">
      {/* Global Search and Navigation Suggestions */}
      <div className="relative w-64 md:w-80" ref={dropdownRef}>
        <div className="relative">
          <button
            type="button"
            onClick={() => {
              if (suggestions.length > 0) {
                handleNavigate(suggestions[0].href);
              }
            }}
            className="absolute left-3 top-1/2 -translate-y-1/2 text-white/50 hover:text-white transition-colors flex items-center justify-center"
            title="Navigate to match"
          >
            <Search size={16} />
          </button>
          <input
            type="text"
            placeholder="Type page keyword (e.g. programs)..."
            value={query}
            onChange={(e) => {
              setQuery(e.target.value);
              setShowSuggestions(true);
            }}
            onFocus={() => setShowSuggestions(true)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && suggestions.length > 0) {
                handleNavigate(suggestions[0].href);
              }
            }}
            className="w-full rounded-card border border-white/20 bg-white/10 py-2 pl-9 pr-3 text-sm text-white placeholder:text-white/40 focus:border-white/40 focus:bg-white/20 focus:outline-none focus:ring-2 focus:ring-white/15 transition-all"
          />
        </div>

        {/* Floating Suggestions Dropdown */}
        {showSuggestions && suggestions.length > 0 && (
          <div className="absolute left-0 right-0 mt-2 rounded-card border border-sand-dark/60 bg-white p-2 shadow-lg z-50 max-h-60 overflow-y-auto">
            <div className="px-2 py-1.5 text-[10px] font-bold text-muted uppercase tracking-wider border-b border-sand-light flex items-center gap-1">
              <Navigation size={10} className="text-emerald" /> Navigation Suggestions
            </div>
            <ul className="mt-1 divide-y divide-sand-light">
              {suggestions.map((item) => (
                <li key={item.href}>
                  <button
                    type="button"
                    onClick={() => handleNavigate(item.href)}
                    className="w-full text-left rounded-card px-2.5 py-2 text-xs font-semibold text-ink hover:bg-emerald-light hover:text-emerald transition-colors flex flex-col"
                  >
                    <span>{item.label}</span>
                    <span className="text-[9px] text-muted font-normal mt-0.5">
                      Keywords: {item.keywords.slice(0, 3).join(", ")}
                    </span>
                  </button>
                </li>
              ))}
            </ul>
          </div>
        )}

        {/* Suggestions Help hint if query doesn't match */}
        {showSuggestions && query.trim() !== "" && suggestions.length === 0 && (
          <div className="absolute left-0 right-0 mt-2 rounded-card border border-sand-dark/60 bg-white p-3 shadow-lg z-50 text-center text-xs text-muted">
            <HelpCircle size={18} className="mx-auto text-muted mb-1" />
            No matching pages. Try "programs", "merit", "certificates" or "profile".
          </div>
        )}
      </div>

      {/* Profile Link and Actions */}
      <div className="flex items-center gap-3">
        <Link
          href={profileHref}
          title="My profile"
          className="flex items-center gap-3 rounded-card px-1.5 py-1 hover:bg-white/10 transition-colors"
        >
          <div className="hidden text-right sm:block leading-tight">
            <p className="text-xs font-semibold text-white">{name}</p>
            <p className="text-[10px] text-white/70">{email}</p>
          </div>
          {avatarUrl ? (
            <img
              src={avatarUrl}
              alt={name}
              className="h-9 w-9 rounded-full border border-white/25 object-cover shadow-sm"
            />
          ) : (
            <div className="flex h-9 w-9 items-center justify-center rounded-full bg-white/20 border border-white/25 text-xs font-bold text-white shadow-sm">
              {initials || "AD"}
            </div>
          )}
        </Link>
        <button
          onClick={() => setShowConfirm(true)}
          title="Sign out"
          className="rounded-card p-2 text-white/70 hover:bg-white/10 hover:text-white transition-colors"
        >
          <LogOut size={18} />
        </button>
      </div>

      {/* Logout Confirmation Modal */}
      <Modal open={showConfirm} onClose={() => setShowConfirm(false)} title="Confirm Sign Out">
        <div className="space-y-4 p-1">
          <p className="text-sm text-muted">
            Are you sure you want to sign out? This will end your current session and require you to sign in again next time.
          </p>
          <div className="flex justify-end gap-2 border-t border-sand-light pt-3">
            <Button variant="secondary" onClick={() => setShowConfirm(false)}>
              Cancel
            </Button>
            <Button variant="danger" onClick={signOut}>
              Sign Out
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}