/*!
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
import { Center, Flex } from "@chakra-ui/react";
import { useRef, type ReactNode } from "react";
import { NavLink, useLocation } from "react-router-dom";

import { useContainerWidth } from "src/utils";

export type NavTab = {
  readonly icon?: ReactNode;
  readonly label: string;
  /** Additional route segments that should also mark this tab as active. */
  readonly matchPaths?: Array<string>;
  readonly value: string;
};

type Props = {
  readonly tabs: Array<NavTab>;
};

export const NavTabs = ({ tabs }: Props) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const containerWidth = useContainerWidth(containerRef);
  const { pathname } = useLocation();
  // Last path segment, e.g. "task-store" or "xcom"
  const lastSegment = pathname.split("/").pop() ?? "";

  return (
    <Flex
      alignItems="center"
      borderBottomColor="border.emphasized"
      borderBottomWidth={1}
      mb={2}
      ref={containerRef}
    >
      {tabs.map(({ icon, label, matchPaths, value }) => {
        const isPathMatch = (matchPaths ?? []).includes(lastSegment);

        return (
          <NavLink
            end
            key={value}
            title={label}
            to={{
              pathname: value,
            }}
          >
            {({ isActive }) => {
              const active = isActive || isPathMatch;

              return (
                <Center
                  _hover={{ color: "fg" }}
                  borderBottomColor="border.info"
                  borderBottomWidth={active ? 3 : 0}
                  color={active ? "fg" : "fg.muted"}
                  fontWeight="bold"
                  height="40px"
                  mb="-2px" // Show the border on top of its parent's border
                  pb={active ? 0 : "3px"}
                  px={4}
                  transition="all 0.2s ease"
                >
                  {containerWidth > 600 || !Boolean(icon) ? label : icon}
                </Center>
              );
            }}
          </NavLink>
        );
      })}
    </Flex>
  );
};
