"use client";

import React, { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Dialog,
  DialogPanel,
  Disclosure,
  DisclosureButton,
  DisclosurePanel,
  Popover,
  PopoverButton,
  PopoverGroup,
  PopoverPanel,
} from "@headlessui/react";
import {
  IconAdjustments,
  IconArrowLeft,
  IconBrandWordpress,
  IconChartArrowsVertical,
  IconChevronDown,
  IconCode,
  IconMenu2,
  IconX,
  type TablerIcon,
} from "@tabler/icons-react";

import type { Dictionary } from "@/app/[lang]/dictionaries";
import { blogCategories } from "@/lib/blog/categories";
import { loginUrl, signupUrl } from "@/lib/env";
import { cn } from "@/lib/utils";
import type { DocsSearchRecord } from "@/lib/search/site-index";
import { LanguageSwitcher } from "@/components/shared/language-switcher";
import { ModeToggle } from "@/components/shared/mode-toggle";
import { SiteSearch } from "@/components/shared/site-search";
import { Logo } from "@/components/shared/logo";
import { Button } from "@/components/ui/button";
import { Container } from "@/components/ui/container";

type NavDict = Dictionary["nav"];
type NavProps = { dict: NavDict; lang: string; records: DocsSearchRecord[] };

const useNavlinks = (dict: NavDict, lang: string) => [
  { title: dict.blog, href: `/${lang}/blog` },
  { title: dict.docs, href: `/${lang}/docs` },
  { title: dict.pricing, href: `/${lang}/pricing` },
];

type ServiceItem = {
  name: string;
  description: string;
  href: string;
  icon: TablerIcon;
};

const useServices = (dict: NavDict, lang: string): ServiceItem[] => {
  const s = dict.servicesItems;
  return [
    {
      ...s.seoCode,
      href: `/${lang}/services/seo-code-optimization`,
      icon: IconCode,
    },
    {
      ...s.wpManagement,
      href: `/${lang}/services/wordpress-management`,
      icon: IconBrandWordpress,
    },
    {
      ...s.wpSeo,
      href: `/${lang}/services/wordpress-seo`,
      icon: IconChartArrowsVertical,
    },
    {
      ...s.cmsOptimization,
      href: `/${lang}/services/cms-optimization`,
      icon: IconAdjustments,
    },
  ];
};

export const Navbar = ({ dict, lang, records }: NavProps) => {
  const pathname = usePathname();
  // Blog gets its own search-forward bar; everything else gets the floating pill.
  const isBlog = /^\/[^/]+\/blog(\/|$)/.test(pathname ?? "");

  if (isBlog) {
    return <BlogNavbar dict={dict} lang={lang} records={records} />;
  }

  return (
    <>
      <div className="fixed inset-x-0 top-0 z-50">
        <div className="mx-auto mt-4 max-w-6xl px-4">
          <div className="bg-background/80 ring-hairline rounded-full shadow-lg ring-1 backdrop-blur-xl">
            <DesktopNavbar dict={dict} lang={lang} records={records} floating />
            <MobileNavbar dict={dict} lang={lang} records={records} />
          </div>
        </div>
      </div>
      {/* Spacer offsets the floating pill (mt-4 + bar height). */}
      <div aria-hidden className="h-[73px] lg:h-[89px]" />
    </>
  );
};

// Brand lockup with the BLOG tag, shared by the blog navbar's two breakpoints.
const BlogBrand = ({ lang }: { lang: string }) => (
  <div className="flex items-center gap-2">
    <Logo lang={lang} />
    <span className="font-display text-brand-orange border-brand-orange/40 rounded-md border px-1.5 py-0.5 text-[11px] font-bold tracking-wide">
      BLOG
    </span>
  </div>
);

const BlogChip = ({
  href,
  active,
  children,
}: {
  href: string;
  active: boolean;
  children: React.ReactNode;
}) => (
  <Link
    href={href}
    aria-current={active ? "page" : undefined}
    style={active ? { backgroundImage: "var(--gradient-brand)" } : undefined}
    className={cn(
      "shrink-0 rounded-full px-3.5 py-1.5 text-[13px] font-semibold whitespace-nowrap transition-colors",
      active
        ? "text-white"
        : "text-ink-3 hover:text-ink-1 hover:bg-foreground/5",
    )}
  >
    {children}
  </Link>
);

// Blog navbar — "Recherche au centre": brand + featured search + back-to-site,
// with a persistent category-chip reminder row underneath.
const BlogNavbar = ({ dict, lang, records }: NavProps) => {
  const pathname = usePathname();
  // First path segment after /blog → active category (null on the index).
  const activeCat =
    (pathname ?? "").match(/^\/[^/]+\/blog(?:\/([^/]+))?/)?.[1] ?? null;

  return (
    <div className="bg-background/72 border-hairline sticky top-0 z-50 border-b backdrop-blur-xl">
      {/* desktop: brand · centered search · lang/theme/back-to-site */}
      <div className="hidden grid-cols-[auto_1fr_auto] items-center gap-6 px-6 py-3 lg:grid">
        <BlogBrand lang={lang} />
        <div className="mx-auto w-full max-w-[440px]">
          <SiteSearch
            variant="bar"
            records={records}
            lang={lang}
            label={dict.searchLabel}
            placeholder={dict.searchArticles}
          />
        </div>
        <div className="flex items-center gap-3 justify-self-end">
          <LanguageSwitcher lang={lang} />
          <ModeToggle />
          <span aria-hidden className="bg-foreground/10 h-6 w-px" />
          <Link
            href={`/${lang}`}
            className="text-ink-2 hover:text-ink-1 inline-flex items-center gap-1.5 text-sm font-medium transition-colors"
          >
            <IconArrowLeft className="size-4" />
            {dict.backToSite}
          </Link>
        </div>
      </div>

      {/* mobile: brand · search · theme · back-to-site */}
      <div className="flex items-center justify-between px-4 py-2.5 lg:hidden">
        <BlogBrand lang={lang} />
        <div className="flex items-center gap-1">
          <SiteSearch
            records={records}
            lang={lang}
            label={dict.searchLabel}
            placeholder={dict.searchArticles}
          />
          <ModeToggle />
          <Link
            href={`/${lang}`}
            aria-label={dict.backToSite}
            className="text-ink-2 hover:bg-foreground/5 -m-2.5 inline-flex items-center justify-center rounded-lg p-2.5 transition-colors"
          >
            <IconArrowLeft className="size-5" />
          </Link>
        </div>
      </div>

      {/* category reminder row */}
      <div className="border-hairline border-t">
        <div className="flex [scrollbar-width:none] items-center gap-2 overflow-x-auto px-4 py-2.5 lg:px-6 [&::-webkit-scrollbar]:hidden">
          <BlogChip href={`/${lang}/blog`} active={activeCat === null}>
            {dict.allArticles}
          </BlogChip>
          {blogCategories.map((c) => (
            <BlogChip
              key={c.slug}
              href={`/${lang}/blog/${c.slug}`}
              active={activeCat === c.slug}
            >
              {c.name}
            </BlogChip>
          ))}
        </div>
      </div>
    </div>
  );
};

const MobileNavbar = ({ dict, lang, records }: NavProps) => {
  const [open, setOpen] = useState(false);
  const navlinks = useNavlinks(dict, lang);
  const services = useServices(dict, lang);
  return (
    <div className="flex items-center justify-between px-4 py-2 md:hidden">
      <Logo lang={lang} />
      <div className="flex items-center gap-1">
        <SiteSearch
          records={records}
          lang={lang}
          label={dict.searchLabel}
          placeholder={dict.searchPlaceholder}
        />
        <button
          type="button"
          onClick={() => setOpen(true)}
          aria-label="Open menu"
          className="text-ink-2 -m-2.5 inline-flex items-center justify-center p-2.5"
        >
          <IconMenu2 className="size-5" />
        </button>
      </div>

      {/* Headless UI Dialog: portals to <body>, traps focus, locks scroll and
          closes on Esc / backdrop click out of the box. */}
      <Dialog
        open={open}
        onClose={setOpen}
        className="relative z-[60] md:hidden"
      >
        <div
          className="fixed inset-0 bg-black/40 backdrop-blur-sm"
          aria-hidden="true"
        />
        <DialogPanel
          transition
          className="bg-background ring-hairline fixed inset-y-0 right-0 flex w-full flex-col overflow-y-auto p-6 transition duration-300 ease-out data-[closed]:translate-x-full sm:max-w-sm sm:ring-1"
        >
          <div className="flex items-center justify-between">
            <Logo lang={lang} />
            <button
              type="button"
              onClick={() => setOpen(false)}
              aria-label="Close menu"
              className="text-ink-2 -m-2.5 p-2.5"
            >
              <IconX className="size-5" />
            </button>
          </div>

          <div className="divide-hairline mt-6 flow-root divide-y">
            <div className="flex flex-col gap-1 py-6">
              <Disclosure as="div">
                <DisclosureButton className="group text-ink-2 hover:bg-foreground/5 -mx-3 flex w-full items-center justify-between rounded-lg px-3 py-2 text-base font-semibold transition-colors">
                  {dict.services}
                  <IconChevronDown className="size-5 transition-transform group-data-[open]:rotate-180" />
                </DisclosureButton>
                <DisclosurePanel className="mt-1 flex flex-col gap-1">
                  {services.map((item) => (
                    <Link
                      key={item.href}
                      href={item.href}
                      onClick={() => setOpen(false)}
                      className="text-ink-3 hover:bg-foreground/5 -mx-3 flex items-center gap-3 rounded-lg px-3 py-2 pl-6 text-sm font-medium transition-colors"
                    >
                      <item.icon className="text-ink-4 size-5 shrink-0" />
                      {item.name}
                    </Link>
                  ))}
                  <Link
                    href={`/${lang}/services`}
                    onClick={() => setOpen(false)}
                    className="text-ink-2 hover:bg-foreground/5 -mx-3 rounded-lg px-3 py-2 pl-6 text-sm font-semibold transition-colors"
                  >
                    {dict.servicesViewAll}
                  </Link>
                </DisclosurePanel>
              </Disclosure>

              {navlinks.map((item) => (
                <Link
                  key={item.title}
                  href={item.href}
                  onClick={() => setOpen(false)}
                  className="text-ink-2 hover:bg-foreground/5 -mx-3 rounded-lg px-3 py-2 text-base font-semibold transition-colors"
                >
                  {item.title}
                </Link>
              ))}
            </div>

            <div className="flex flex-col gap-4 py-6">
              <div className="flex items-center gap-4">
                <LanguageSwitcher lang={lang} />
                <ModeToggle />
              </div>
              <a
                href={loginUrl}
                onClick={() => setOpen(false)}
                className="text-ink-2 hover:bg-foreground/5 -mx-3 rounded-lg px-3 py-2 text-base font-semibold transition-colors"
              >
                {dict.login}
              </a>
              <Button asChild className="w-full">
                <a href={signupUrl} onClick={() => setOpen(false)}>
                  {dict.signup}
                </a>
              </Button>
            </div>
          </div>
        </DialogPanel>
      </Dialog>
    </div>
  );
};

const DesktopNavbar = ({
  dict,
  lang,
  records,
  floating,
}: NavProps & { floating?: boolean }) => {
  const navlinks = useNavlinks(dict, lang);
  const services = useServices(dict, lang);
  const Wrapper = floating ? "div" : Container;
  const wrapperClass = floating
    ? "hidden items-center justify-between px-6 py-3 lg:flex"
    : "hidden items-center justify-between py-4 lg:flex";
  return (
    <Wrapper className={wrapperClass}>
      <Logo lang={lang} />
      <PopoverGroup className="flex items-center gap-10">
        <Popover className="relative">
          <PopoverButton className="flex items-center gap-1 text-sm font-medium text-neutral-600 outline-none dark:text-neutral-400">
            {dict.services}
            <IconChevronDown className="size-4" aria-hidden="true" />
          </PopoverButton>
          <PopoverPanel
            transition
            className="bg-background ring-hairline absolute top-full left-1/2 z-50 mt-4 w-screen max-w-lg -translate-x-1/2 overflow-hidden rounded-2xl shadow-2xl ring-1 transition data-[closed]:translate-y-1 data-[closed]:opacity-0 data-[enter]:duration-200 data-[leave]:duration-150"
          >
            <div className="grid grid-cols-2 gap-2 p-3">
              {services.map((item) => (
                <Link
                  key={item.href}
                  href={item.href}
                  className="group hover:bg-foreground/5 flex flex-col gap-2 rounded-xl p-4 transition-colors"
                >
                  <div className="bg-surface-2 flex size-10 items-center justify-center rounded-lg">
                    <item.icon
                      className="text-ink-2 size-5"
                      aria-hidden="true"
                    />
                  </div>
                  <div className="text-ink-1 text-sm font-semibold">
                    {item.name}
                  </div>
                  <p className="text-ink-4 text-xs leading-relaxed">
                    {item.description}
                  </p>
                </Link>
              ))}
            </div>
            <Link
              href={`/${lang}/services`}
              className="border-hairline text-ink-2 hover:bg-foreground/5 block border-t px-5 py-3 text-sm font-semibold transition-colors"
            >
              {dict.servicesViewAll}
              <span aria-hidden="true"> &rarr;</span>
            </Link>
          </PopoverPanel>
        </Popover>

        {navlinks.map((item) => (
          <Link
            key={item.title}
            href={item.href}
            className="text-sm font-medium text-neutral-600 dark:text-neutral-400"
          >
            {item.title}
          </Link>
        ))}
      </PopoverGroup>
      <div className="flex items-center gap-4">
        <SiteSearch
          records={records}
          lang={lang}
          label={dict.searchLabel}
          placeholder={dict.searchPlaceholder}
        />
        <LanguageSwitcher lang={lang} />
        <ModeToggle />
        <a
          href={loginUrl}
          className="inline-block rounded-md px-4 py-2 text-sm font-medium text-neutral-600 dark:text-neutral-400"
        >
          {dict.login}
        </a>
        <Button asChild>
          <a href={signupUrl}>{dict.signup}</a>
        </Button>
      </div>
    </Wrapper>
  );
};
