import PageHeader from "@/layouts/shared/page.header";
import { PromoThemeShell } from "@/routes/promo-code-campaigns/_components/PromoThemeShell";
import { AppShellSection, Box } from "@mantine/core";
import {
  IconBell,
  IconReportAnalytics,
  IconSettings,
  IconStack2,
} from "@tabler/icons-react";
import { useEffect, useState } from "react";
import { Outlet, useLocation, useSearchParams } from "react-router";

const BASE = "/admin/notifications";

const LINKS = [
  {
    Icon: IconStack2,
    label: "Campaigns",
    href: `${BASE}?tab=campaigns`,
    tab: "campaigns",
  },
  {
    Icon: IconBell,
    label: "All Notifications",
    href: `${BASE}?tab=notifications`,
    tab: "notifications",
  },
  {
    Icon: IconReportAnalytics,
    label: "Reports",
    href: `${BASE}?tab=reports`,
    tab: "reports",
  },
  {
    Icon: IconSettings,
    label: "Settings",
    href: `${BASE}/settings`,
    tab: "settings",
  },
];

const activeTabFor = (pathname: string, tabParam: string | null) => {
  if (pathname.startsWith(`${BASE}/settings`)) return "settings";
  return tabParam || "campaigns";
};

const NotificationsLayout = () => {
  const { pathname } = useLocation();
  const [searchParams] = useSearchParams();
  const resolveIndex = () =>
    LINKS.findIndex(
      (link) => link.tab === activeTabFor(pathname, searchParams.get("tab")),
    );
  const [activeIndex, setActiveIndex] = useState(resolveIndex);

  useEffect(() => {
    setActiveIndex(resolveIndex());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname, searchParams]);

  return (
    <AppShellSection>
      <PageHeader
        links={LINKS}
        activeIndex={activeIndex}
        setActiveIndex={setActiveIndex}
      />
      <PromoThemeShell>
        <Box py={20} px={28}>
          <Outlet />
        </Box>
      </PromoThemeShell>
    </AppShellSection>
  );
};

export default NotificationsLayout;
