import { useCallback, useEffect, useState } from "react";

/**
 * Read the current `?provider=…` query param off `window.location.search`.
 * Returns `null` when the param is absent or empty.
 *
 * `URLSearchParams` is the standard, locale-free way to parse query
 * strings in the browser. Using it (rather than hand-rolled string
 * slicing) means we correctly handle multiple params and percent-encoded
 * characters in NPIs without surprises.
 *
 * Param name is `?provider=` — chosen to mirror the existing
 * `?provider=NPI` drilldown convention used by the dashboard's
 * "Top providers" row (so deep links survive across the app) and to
 * stay alphabetically parallel with `?claim=` and `?remit=` (one-word
 * tokens, no collision with the existing `MatchedProviderCard`).
 */
function readProviderNpi(): string | null {
  const params = new URLSearchParams(window.location.search);
  const value = params.get("provider");
  return value === "" ? null : value;
}

/**
 * Build the URL we want to push/replace into history.
 *
 * - `providerNpi === null`  →  drop the `?provider=` param, preserving
 *   any other params (e.g. `?page=2&provider=…` keeps `page=2`).
 * - `providerNpi !== null`  →  set the param to the new NPI, also
 *   preserving any other params.
 *
 * We return `pathname + search + hash` (a relative URL) rather than the
 * full href — `history.pushState` accepts a relative URL and rewriting
 * only the relative form keeps the document's origin stable.
 */
function buildUrl(providerNpi: string | null): string {
  const url = new URL(window.location.href);
  if (providerNpi === null) {
    url.searchParams.delete("provider");
  } else {
    url.searchParams.set("provider", providerNpi);
  }
  return url.pathname + url.search + url.hash;
}

/**
 * Per-provider detail drawer URL state (ProviderDrawer).
 *
 * Mirrors `useRemitDrawerUrlState` but for the providers drawer — reads
 * `?provider=` from the URL on mount and keeps the value in sync with
 * history as the drawer is opened, navigated (j/k), and closed.
 *
 *   - `providerNpi`: the NPI parsed from the URL (or `null` when the
 *     param is absent). React state so consumers re-render on changes.
 *   - `open(npi)`: pushes a NEW history entry with `?provider={npi}` —
 *     so the browser Back button returns to the previous page (e.g. the
 *     providers list) and not just to the previously-open provider.
 *   - `setProviderNpi(npi)`: REPLACES the current history entry — used
 *     by the j/k nav handler so j/k moves through the list without
 *     polluting history with one entry per keystroke.
 *   - `close()`: pushes a NEW entry that strips the param, so Back from
 *     the closed drawer returns to whatever page the user was on before
 *     opening the drawer.
 *
 * The hook subscribes to `popstate` so that browser Back/Forward
 * (which fire popstate rather than our own pushState) propagate into
 * the React state. Without this, hitting Back would change the URL but
 * leave the drawer open on the stale NPI.
 */
export function useProviderDrawerUrlState(): {
  providerNpi: string | null;
  open: (npi: string) => void;
  close: () => void;
  setProviderNpi: (npi: string) => void;
} {
  const [providerNpi, setProviderNpiState] = useState<string | null>(() => readProviderNpi());

  const open = useCallback((npi: string) => {
    window.history.pushState(null, "", buildUrl(npi));
    setProviderNpiState(npi);
  }, []);

  const setProviderNpi = useCallback((npi: string) => {
    window.history.replaceState(null, "", buildUrl(npi));
    setProviderNpiState(npi);
  }, []);

  const close = useCallback(() => {
    window.history.pushState(null, "", buildUrl(null));
    setProviderNpiState(null);
  }, []);

  useEffect(() => {
    const onPopState = () => {
      setProviderNpiState(readProviderNpi());
    };
    window.addEventListener("popstate", onPopState);
    return () => window.removeEventListener("popstate", onPopState);
  }, []);

  return { providerNpi, open, close, setProviderNpi };
}