import { Link, useRouterState } from "@tanstack/react-router";
import { useEffect, useMemo, useRef, useState } from "react";
import { Menu, Search, ShieldCheck, X } from "lucide-react";
import { units } from "@/lib/units";
import { Logo } from "./Logo";

const nav = [
  { to: "/", label: "Home" },
  { to: "/about", label: "About" },
  { to: "/businesses", label: "Businesses & Industries" },
  { to: "/foundation", label: "Foundation" },
  { to: "/news", label: "News" },
  { to: "/careers", label: "Careers" },
  { to: "/contact", label: "Contact" },
] as const;

const searchPages = [
  {
    title: "Home",
    description: "Vigor Group of Companies overview",
    to: "/",
  },
  {
    title: "About",
    description: "Our story, purpose, founder and leadership",
    to: "/about",
  },
  {
    title: "Businesses",
    description: "Explore the companies in the Vigor portfolio",
    to: "/businesses",
  },
  {
    title: "Foundation",
    description: "Community development and social impact",
    to: "/foundation",
  },
  {
    title: "Leadership",
    description: "Meet the people leading Vigor Group",
    to: "/leadership",
  },
  {
    title: "News",
    description: "Latest stories and company updates",
    to: "/news",
  },
  {
    title: "Careers",
    description: "Career opportunities across the group",
    to: "/careers",
  },
  {
    title: "Contact",
    description: "Contact Vigor Group of Companies",
    to: "/contact",
  },

  ...units.map((unit) => ({
    title: unit.name,
    description: `${unit.sector} · ${unit.location} · ${unit.blurb}`,
    to: `/businesses/${unit.slug}`,
  })),
];

function isCurrentRoute(pathname: string, route: string) {
  if (route === "/") {
    return pathname === "/";
  }

  return pathname === route || pathname.startsWith(`${route}/`);
}

export function Header() {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

  const searchInputRef = useRef<HTMLInputElement>(null);

  const pathname = useRouterState({
    select: (state) => state.location.pathname,
  });

  const overHero = pathname === "/";

  useEffect(() => {
    const handleScroll = () => {
      setScrolled(window.scrollY > 24);
    };

    handleScroll();

    window.addEventListener("scroll", handleScroll, {
      passive: true,
    });

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  useEffect(() => {
    setMobileMenuOpen(false);
    setSearchOpen(false);
    setSearchQuery("");
  }, [pathname]);

  useEffect(() => {
    if (!searchOpen) {
      return;
    }

    const focusTimer = window.setTimeout(() => {
      searchInputRef.current?.focus();
    }, 50);

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setSearchOpen(false);
      }
    };

    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", handleKeyDown);

    return () => {
      window.clearTimeout(focusTimer);
      document.body.style.overflow = "";
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [searchOpen]);

  const searchResults = useMemo(() => {
    const value = searchQuery.trim().toLowerCase();

    if (!value) {
      return searchPages.slice(0, 8);
    }

    return searchPages.filter((item) => {
      const searchableText =
        `${item.title} ${item.description}`.toLowerCase();

      return searchableText.includes(value);
    });
  }, [searchQuery]);

  const solidHeader = scrolled || !overHero || mobileMenuOpen;

  return (
    <>
      <header
        className={`fixed inset-x-0 top-0 z-50 transition-colors duration-300 ${
          solidHeader
            ? "border-b border-border bg-background/95 backdrop-blur"
            : "border-b border-white/15 bg-transparent"
        }`}
      >
        <div className="container-x grid h-16 grid-cols-[minmax(0,1fr)_auto] items-center gap-4 md:h-20">
          <Link
            to="/"
            className="flex min-w-0 items-center"
            aria-label="Vigor Group home"
          >
            <Logo size="sm" light={!solidHeader} />
          </Link>

          <div className="flex items-center gap-5">
            <nav
              className="hidden items-center gap-6 lg:flex"
              aria-label="Primary navigation"
            >
              {nav.slice(1).map((item) => {
                const active = isCurrentRoute(pathname, item.to);

                return (
                  <Link
                    key={item.to}
                    to={item.to}
                    aria-current={active ? "page" : undefined}
                    className={`relative py-2 text-[0.82rem] font-bold uppercase tracking-[0.08em] transition-colors hover:text-crimson after:absolute after:bottom-[-2px] after:left-0 after:right-0 after:h-0.5 after:origin-left after:transition-transform ${
                      active
                        ? "text-crimson after:scale-x-100 after:bg-crimson"
                        : `${
                            solidHeader
                              ? "text-foreground"
                              : "text-white"
                          } after:scale-x-0`
                    }`}
                  >
                    {item.label}
                  </Link>
                );
              })}
            </nav>

            <div className="hidden items-center gap-3 border-l border-current/20 pl-5 lg:flex">
              <Link
                to="/whistleblower"
                className={`inline-flex items-center gap-2 rounded-full border px-3.5 py-1.5 text-[0.72rem] font-bold uppercase tracking-[0.1em] transition-colors ${
                  solidHeader
                    ? "border-crimson/40 text-crimson hover:bg-crimson hover:text-white"
                    : "border-white/40 text-white hover:bg-white hover:text-crimson"
                }`}
              >
                <ShieldCheck size={15} />
                Whistleblower
              </Link>

              <button
                type="button"
                aria-label="Search the website"
                onClick={() => setSearchOpen(true)}
                className={`rounded-full p-2 transition-colors hover:bg-crimson/10 hover:text-crimson ${
                  solidHeader
                    ? "text-ink-soft"
                    : "text-white/85"
                }`}
              >
                <Search size={17} />
              </button>
            </div>


            <button
              type="button"
              className={`-mr-2 p-2 lg:hidden ${
                solidHeader
                  ? "text-foreground"
                  : "text-white"
              }`}
              onClick={() => {
                setMobileMenuOpen((value) => !value);
              }}
              aria-label="Toggle navigation menu"
              aria-expanded={mobileMenuOpen}
            >
              {mobileMenuOpen ? (
                <X size={22} />
              ) : (
                <Menu size={22} />
              )}
            </button>
          </div>
        </div>

        {mobileMenuOpen && (
          <div className="border-t border-border bg-background lg:hidden">
            <nav
              className="container-x flex flex-col py-5"
              aria-label="Mobile navigation"
            >
              {nav.map((item) => {
                const active = isCurrentRoute(pathname, item.to);

                return (
                  <Link
                    key={item.to}
                    to={item.to}
                    aria-current={active ? "page" : undefined}
                    onClick={() => setMobileMenuOpen(false)}
                    className={`border-b border-border py-3 text-base transition-colors ${
                      active
                        ? "font-bold text-crimson"
                        : "font-medium text-foreground hover:text-crimson"
                    }`}
                  >
                    {item.label}
                  </Link>
                );
              })}

              <Link
                to="/whistleblower"
                onClick={() => setMobileMenuOpen(false)}
                className="mt-5 inline-flex items-center justify-center gap-2 rounded-full border border-crimson/40 px-4 py-2 text-xs font-bold uppercase tracking-[0.1em] text-crimson transition-colors hover:bg-crimson hover:text-white"
              >
                <ShieldCheck size={15} />
                Whistleblower
              </Link>

              <div className="pt-5 text-sm text-muted-foreground">

                <button
                  type="button"
                  onClick={() => {
                    setMobileMenuOpen(false);
                    setSearchOpen(true);
                  }}
                  className="inline-flex items-center gap-2 transition-colors hover:text-crimson"
                  aria-label="Search the website"
                >
                  <Search size={16} />
                  Search
                </button>
              </div>
            </nav>
          </div>
        )}
      </header>

      {searchOpen && (
        <div
          className="fixed inset-0 z-[100] bg-navy-deep/75 p-4 backdrop-blur-sm md:p-8"
          role="dialog"
          aria-modal="true"
          aria-labelledby="site-search-title"
          onMouseDown={(event) => {
            if (event.currentTarget === event.target) {
              setSearchOpen(false);
            }
          }}
        >
          <div className="mx-auto mt-12 max-w-2xl overflow-hidden rounded-xl border border-border bg-background shadow-2xl md:mt-20">
            <div className="flex items-center gap-3 border-b border-border px-4 md:px-6">
              <Search
                size={20}
                className="shrink-0 text-crimson"
              />

              <input
                ref={searchInputRef}
                value={searchQuery}
                onChange={(event) => {
                  setSearchQuery(event.target.value);
                }}
                placeholder="Search pages, businesses or industries..."
                className="h-16 w-full bg-transparent text-base outline-none placeholder:text-muted-foreground"
                aria-label="Search query"
              />

              <button
                type="button"
                onClick={() => setSearchOpen(false)}
                className="rounded-full p-2 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
                aria-label="Close search"
              >
                <X size={20} />
              </button>
            </div>

            <div className="max-h-[60vh] overflow-y-auto p-2 md:p-3">
              <p
                id="site-search-title"
                className="px-3 py-2 text-xs font-bold uppercase tracking-[0.16em] text-muted-foreground"
              >
                {searchQuery
                  ? `${searchResults.length} result${
                      searchResults.length === 1 ? "" : "s"
                    }`
                  : "Suggested pages"}
              </p>

              {searchResults.length > 0 ? (
                <div className="space-y-1">
                  {searchResults.map((item) => (
                    <a
                      key={item.to}
                      href={item.to}
                      onClick={() => setSearchOpen(false)}
                      className="block rounded-lg px-3 py-3 transition-colors hover:bg-secondary focus:bg-secondary focus:outline-none"
                    >
                      <div className="font-semibold text-foreground">
                        {item.title}
                      </div>

                      <div className="mt-1 text-sm leading-relaxed text-muted-foreground">
                        {item.description}
                      </div>
                    </a>
                  ))}
                </div>
              ) : (
                <div className="px-3 py-10 text-center">
                  <p className="font-semibold">
                    No matching pages found
                  </p>

                  <p className="mt-2 text-sm text-muted-foreground">
                    Try a business name, sector, or page such as
                    About, Industries or Contact.
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
