"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { NavIcon } from "@/components/nav-icon";
import { cn } from "@/lib/utils";

const SECTIONS = [
  { id: "household", label: "Household", icon: "people" },
  { id: "sharing", label: "Sharing & links", icon: "link" },
  { id: "notifications", label: "Notifications", icon: "bell" },
  { id: "calendars", label: "Calendars & lists", icon: "calendar" },
  { id: "appearance", label: "Appearance", icon: "sun" },
  { id: "data", label: "Data & backups", icon: "history" },
] as const;

export type SectionId = (typeof SECTIONS)[number]["id"];

export function SettingsSidebar({ active }: { active: SectionId }) {
  const router = useRouter();
  const pathname = usePathname();

  return (
    <nav
      className="rounded-[var(--r-lg)] border-[0.5px] bg-[var(--card)] shadow-[var(--shadow-1)] h-fit"
      style={{ borderColor: "var(--hair)" }}
      aria-label="Settings sections"
    >
      <div className="card-h">
        <h3 className="serif text-[15px] m-0 font-medium">Settings</h3>
      </div>
      <div className="p-1.5">
        {SECTIONS.map((s) => (
          <button
            key={s.id}
            type="button"
            className={cn("nav-item h-9")}
            aria-current={active === s.id ? "page" : undefined}
            onClick={() => {
              const url = new URL(window.location.href);
              url.searchParams.set("s", s.id);
              router.replace(url.pathname + "?" + url.searchParams.toString() + url.hash, {
                scroll: false,
              });
            }}
          >
            <NavIcon name={s.icon} className="size-4" />
            <span className="nav-label">{s.label}</span>
          </button>
        ))}
        <div className="nav-divider" />
        <Link href="/settings/household" className="nav-item h-9">
          <NavIcon name="users" className="size-4" />
          <span className="nav-label">Manage household</span>
        </Link>
      </div>
      <SectionHashSync pathname={pathname} />
    </nav>
  );
}

// When the URL changes with a hash like #sharing (used by sidebar Share-links link),
// ensure the matching section opens.
function SectionHashSync({ pathname }: { pathname: string | null }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  useEffect(() => {
    if (typeof window === "undefined") return;
    const hash = window.location.hash.slice(1);
    if (!hash) return;
    if (!SECTIONS.some((s) => s.id === hash)) return;
    if (searchParams?.get("s") === hash) return;
    const url = new URL(window.location.href);
    url.searchParams.set("s", hash);
    router.replace(url.pathname + "?" + url.searchParams.toString(), { scroll: false });
  }, [pathname, router, searchParams]);
  return null;
}

export function SettingsTabsMobile({ active }: { active: SectionId }) {
  const router = useRouter();
  return (
    <div className="seg w-full overflow-x-auto" style={{ display: "flex" }}>
      {SECTIONS.map((s) => (
        <button
          key={s.id}
          type="button"
          role="tab"
          aria-selected={active === s.id}
          onClick={() => {
            const url = new URL(window.location.href);
            url.searchParams.set("s", s.id);
            router.replace(url.pathname + "?" + url.searchParams.toString(), { scroll: false });
          }}
        >
          {s.label.split(" ")[0]}
        </button>
      ))}
    </div>
  );
}

export function ResponsiveSidebar({ active }: { active: SectionId }) {
  const [isMobile, setIsMobile] = useState(false);
  useEffect(() => {
    const mq = window.matchMedia("(max-width: 759px)");
    const apply = () => setIsMobile(mq.matches);
    apply();
    mq.addEventListener("change", apply);
    return () => mq.removeEventListener("change", apply);
  }, []);
  if (isMobile) return <SettingsTabsMobile active={active} />;
  return <SettingsSidebar active={active} />;
}
