import { useLocation, useMatch, useNavigate } from 'react-router';

import { HostsTree } from '../common/HostsTree';
import type { NodeContext } from '../common/HostsTree';

export const LeftSidebar = () => {
  const navigate = useNavigate();
  const location = useLocation();

  // LeftSidebar lives outside the <Routes> block, so `useParams` returns
  // nothing for it. Use `useMatch` against the host detail route pattern to
  // pick the current hostkey from the URL so we can highlight the active row.
  const hostMatch = useMatch('/:hostkey');
  const rawHostkey =
    hostMatch?.params.hostkey && hostMatch.params.hostkey !== 'label'
      ? hostMatch.params.hostkey
      : undefined;

  const handleHostSelect = (key: string) => {
    // Preserve the query string (e.g. `?tab=containers`) so the active host
    // detail tab carries across host switches, not just reloads.
    navigate({ pathname: `/${key}`, search: location.search });
  };

  const handleNodeSelect = (ctx: NodeContext) => {
    const params = new URLSearchParams();
    // Empty `inc=` for the "All hosts" root signals "no class filter" — the
    // label page parses it to [] and the API call omits `includes` entirely.
    params.set('inc', ctx.includes.join(','));
    // Excludes are only set for super-nodes ("hosts without category") —
    // TreeNode decides whether to pass them.
    if (ctx.excludes.length > 0) params.set('exc', ctx.excludes.join('|'));
    navigate(`/label/${encodeURIComponent(ctx.label)}?${params.toString()}`);
  };

  return (
    <HostsTree
      selectedHostkey={rawHostkey}
      onHostSelect={handleHostSelect}
      onNodeSelect={handleNodeSelect}
    />
  );
};
