import { useEffect, useState } from "react";
import { isMobile } from "react-device-detect";
import { useNavigate, useLocation } from "react-router-dom";
import { Tab } from "../../../types/tab";
import NavbarDesktop from "./NavbarDesktop";
import NavbarMobile from "./NavbarMobile";
import { tabs } from "../../../consts/tabs";

const Navbar = () => {
  const [selectedTab, setSelectedTab] = useState<Tab | null>(null);
  const location = useLocation();
  useEffect(() => {
    const pathname = location.pathname;
    const tab = tabs.find((tab) => tab.path === pathname);
    const defaultTab = tabs[0];
    if (tab) {
      setSelectedTab(tab);
    } else {
      setSelectedTab(defaultTab);
    }
  }, [location.pathname]);
  const navigate = useNavigate();
  const onTabClick = (tab: Tab) => {
    setSelectedTab(tab);
    navigate(tab.path);
  };

  return (
    <>
      {isMobile ? (
        <NavbarMobile onTabClick={onTabClick} tabs={tabs} />
      ) : (
        <NavbarDesktop
          selectedTab={selectedTab}
          onTabClick={onTabClick}
          tabs={tabs}
        />
      )}
    </>
  );
};

export default Navbar;
