'use client';
import { FunctionComponent, useCallback, useMemo } from 'react';
import { BottomNavigation, BottomNavigationAction, Paper } from '@mui/material';
import { LinkToPage } from '@/utils';
import { AppIcon } from '@/components';
import { usePathname, useRouter } from '@/i18n/navigation';
import { matchActivePath } from '../matchActivePath';

interface Props {
  items: Array<LinkToPage>;
}

/**
 * Shared horizontal navigation bar (customer app tabs, and the nurse shell's mobile 5-tab nav)
 * built on MUI BottomNavigation. Locale-aware via the `@/i18n/navigation` wrapper — no manual
 * `/${locale}` prefixing — and highlights the active tab with the shared `matchActivePath`
 * longest-prefix helper, so a nested route (e.g. `/patients/123`) still selects its parent tab.
 * @component BottomBar
 */
const BottomBar: FunctionComponent<Props> = ({ items }) => {
  const router = useRouter();
  const pathname = usePathname();

  const activePath = useMemo(
    () => matchActivePath(pathname, items.map((item) => item.path)) ?? false,
    [items, pathname]
  );

  const onNavigationChange = useCallback(
    (_event: unknown, newValue: string) => {
      const item = items.find((candidate) => candidate.path === newValue);
      if (item?.onSelect) {
        item.onSelect();
        return;
      }
      router.push(newValue);
    },
    [items, router]
  );

  return (
    <Paper
      elevation={3}
      square
      component="nav"
      sx={{ borderTop: '1px solid', borderColor: 'divider', paddingBottom: 'env(safe-area-inset-bottom)' }}
    >
      <BottomNavigation value={activePath} showLabels onChange={onNavigationChange}>
        {items.map(({ title, path, icon }) => (
          <BottomNavigationAction key={`${title}-${path}`} label={title} value={path} icon={<AppIcon icon={icon} />} />
        ))}
      </BottomNavigation>
    </Paper>
  );
};

export default BottomBar;
