'use client';
import { FunctionComponent, PropsWithChildren, useMemo } from 'react';
import { Box, Stack, Tab, Tabs } from '@mui/material';
import { useTranslations } from 'next-intl';
import { AppIcon, AppIconButton, ErrorBoundary } from '@/components';
import { NotificationBell } from '@/components/notifications';
import { CONTENT_MAX_WIDTH } from '@/components/config';
import { ROUTES } from '@/constants';
import { LinkToPage } from '@/utils';
import { usePathname, useRouter } from '@/i18n/navigation';
import { TopBar, BottomBar } from './components';
import { DarkModeToggleButton } from './components/DarkModeButton';
import BrandLockup from './components/BrandLockup';
import { matchActivePath } from './matchActivePath';
import { PageTitleProvider, isCustomerRootTab, useRouteTitle } from './routeTitle';
import { TOP_BAR_DESKTOP_HEIGHT, TOP_BAR_MOBILE_HEIGHT, TOP_NAV_DESKTOP_HEIGHT } from './config';

/** The ≥md replacement for the mobile BottomBar — the same 5 tabs, inline in the header. */
const CustomerDesktopNav: FunctionComponent<{ items: Array<LinkToPage> }> = ({ items }) => {
  const pathname = usePathname();
  const router = useRouter();
  const activePath = matchActivePath(pathname, items.map((item) => item.path)) ?? false;

  return (
    <Box sx={{ display: { xs: 'none', md: 'block' }, borderTop: '1px solid', borderColor: 'divider' }}>
      <Tabs
        value={activePath}
        onChange={(_event, value: string) => router.push(value)}
        sx={{ minHeight: TOP_NAV_DESKTOP_HEIGHT, px: 2 }}
      >
        {items.map((item) => (
          <Tab
            key={item.path}
            value={item.path}
            label={item.title}
            icon={item.icon ? <AppIcon icon={item.icon} size={18} /> : undefined}
            iconPosition="start"
            sx={{ minHeight: TOP_NAV_DESKTOP_HEIGHT }}
          />
        ))}
      </Tabs>
    </Box>
  );
};

const CustomerHeader: FunctionComponent<{ bottomNavItems: Array<LinkToPage> }> = ({ bottomNavItems }) => {
  const t = useTranslations('nav');
  const tc = useTranslations('common');
  const pathname = usePathname();
  const router = useRouter();
  const title = useRouteTitle();
  const onRootTab = isCustomerRootTab(pathname);

  return (
    <TopBar
      align={onRootTab ? 'center' : 'start'}
      startNode={
        onRootTab ? (
          <AppIconButton
            icon="support"
            color="inherit"
            title={t('support')}
            onClick={() => router.push(ROUTES.SUPPORT_TICKETS)}
          />
        ) : (
          <AppIconButton icon="back" title={tc('back')} onClick={() => router.back()} />
        )
      }
      titleNode={onRootTab ? <BrandLockup /> : undefined}
      title={onRootTab ? undefined : (title ?? undefined)}
      endNode={
        <Stack direction="row" sx={{ alignItems: 'center' }}>
          <NotificationBell role="customer" />
          <DarkModeToggleButton />
        </Stack>
      }
      secondaryRow={<CustomerDesktopNav items={bottomNavItems} />}
    />
  );
};

/**
 * Customer (family) app shell — the primary, mobile-first experience. A contextual TopBar (brand
 * lockup on the 5 root tabs, page title + back chevron on pushed routes), a reading-width content
 * column on a `background.default` canvas, and the 5-tab `BottomBar` on mobile — replaced by an
 * inline desktop top-nav (`CustomerDesktopNav`) at `≥md`, where the mobile tab bar hides entirely.
 * @layout CustomerLayout
 */
const CustomerLayout: FunctionComponent<PropsWithChildren> = ({ children }) => {
  const t = useTranslations('nav');
  const tChrome = useTranslations('routeChrome');

  const bottomNavItems: Array<LinkToPage> = useMemo(
    () => [
      { title: t('home'), path: ROUTES.HOME, icon: 'home' },
      { title: t('bookings'), path: ROUTES.BOOKINGS, icon: 'bookings' },
      { title: t('patients'), path: ROUTES.PATIENTS, icon: 'patients' },
      { title: t('wallet'), path: ROUTES.WALLET, icon: 'wallet' },
      { title: t('profile'), path: ROUTES.PROFILE, icon: 'profile' },
    ],
    [t]
  );

  return (
    <PageTitleProvider>
      <Stack sx={{ height: '100dvh', bgcolor: 'background.default' }}>
        <Stack component="header">
          <CustomerHeader bottomNavItems={bottomNavItems} />
        </Stack>

        <Box
          component="main"
          sx={{
            flexGrow: 1,
            overflowY: 'auto',
            width: '100%',
            // AppBar is position: fixed — offset content by the top-bar (+ desktop top-nav) height.
            pt: {
              xs: `calc(${TOP_BAR_MOBILE_HEIGHT} + 8px)`,
              md: `calc(${TOP_BAR_DESKTOP_HEIGHT} + ${TOP_NAV_DESKTOP_HEIGHT} + 16px)`,
            },
          }}
        >
          <Box sx={{ maxWidth: CONTENT_MAX_WIDTH, mx: 'auto', px: 2, pb: 2 }}>
            <ErrorBoundary
              name="Customer"
              title={tChrome('error_title')}
              body={tChrome('error_body')}
              retryLabel={tChrome('error_retry')}
            >
              {children}
            </ErrorBoundary>
          </Box>
        </Box>

        <Box sx={{ display: { xs: 'block', md: 'none' } }}>
          <BottomBar items={bottomNavItems} />
        </Box>
      </Stack>
    </PageTitleProvider>
  );
};

export default CustomerLayout;
