import { Button, Group } from "@mantine/core";
import type { IconProps } from "@tabler/icons-react";
import React from "react";
import type { PathMatch } from "react-router";
import { Link, matchPath, useLocation } from "react-router";

const PageHeader: React.FC<{
  links: {
    Icon: React.ForwardRefExoticComponent<
      IconProps & React.RefAttributes<SVGSVGElement>
    >;
    label: string;
    href: string;
  }[];
  activeIndex?: number;
  setActiveIndex?: (value: number) => void;
}> = ({ links, activeIndex = 0, setActiveIndex }) => {
  const location = useLocation();
  return (
    <Group
      px={28}
      py={20}
      style={{
        borderBottom: "1px solid var(--mantine-color-white-1)",
      }}
    >
      {links.map((link, id) => {
        // const isActive = matchPath(location.pathname, link.href);
        let isActive: PathMatch<string> | null | boolean;
        if (activeIndex !== undefined && setActiveIndex !== undefined) {
          isActive = id === activeIndex;
        } else {
          isActive = matchPath(location.pathname, link.href);
        }
        return (
          <Button
            key={id}
            variant={isActive ? "filled" : "transparent"}
            size="compact-md"
            color={isActive ? "blue.1" : ""}
            c={isActive ? "blue.9" : "dark.9"}
            autoContrast
            fw={"normal"}
            px={0}
            onClick={() => (setActiveIndex ? setActiveIndex(id) : null)}
          >
            <Link
              to={`${link.href}`}
              style={{
                color: isActive
                  ? "var(--mantine-color-blue-9)"
                  : "var(--mantine-color-dark-9)",
                textDecoration: "none",
                height: "100%",
                width: "100%",
                paddingBlock: "6px",
                paddingInline: "8px",
              }}
            >
              <Group gap={4}>
                <link.Icon size={16} />
                {link.label}
              </Group>
            </Link>
          </Button>
        );
      })}
    </Group>
  );
};

export default PageHeader;
