"use client";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbList,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Fragment, useEffect, useState } from "react";
import useUserStore from "@/store/useUserStore";

type BreadcrumbsT = {
  text: string;
  href: string;
};

const menuList = [
  {
    title: "Customer",
    link: "/customer",
  },
  {
    title: "User",
    link: "/user",
    restricted: true,
  },
];

const MenuBar = () => {
  const pathname = usePathname();
  const [pathnamesState, setPathnamesState] = useState<BreadcrumbsT[]>([]);
  const data = useUserStore((state) => state.data);

  useEffect(() => {
    const pathnames = pathname.split("/").filter((x) => x);

    const breadcrumbs = pathnames.map((_, index) => {
      return {
        text: pathnames[index].charAt(0).toUpperCase() + pathnames[index].slice(1),
        href: `${pathnames.slice(0, index + 1).join("/")}`,
      };
    });

    setPathnamesState(breadcrumbs);
  }, [pathname]);

  const allowedRoles = ["Admin", "Owner"];
  const employeePermissions = [
    "Can add employees",
    "Can change employees",
    "Can delete employees",
    "Can view employees",
  ];

  // Determine access to User module
  const hasAccess =
    data &&
    (allowedRoles.includes(data.role) ||
      (!allowedRoles.includes(data.role) &&
        data.permissions?.some((perm) =>
          employeePermissions.includes(perm.name)
        )));

  return (
    <div className="bg-primary/50 py-2 px-10 flex justify-between items-center">
      <Breadcrumb>
        <BreadcrumbList>
          {pathnamesState.map((path, index) => (
            <Fragment key={index}>
              <BreadcrumbItem>
                <Link className="text-xl text-white" href={"/" + path.href}>
                  {path.text}
                </Link>
              </BreadcrumbItem>
              <BreadcrumbSeparator />
            </Fragment>
          ))}
        </BreadcrumbList>
      </Breadcrumb>

      <div className="flex gap-5 text-sm">
        {menuList
          .filter((link) => {
            if (link.restricted) {
              return hasAccess; // Show restricted items only for allowed users
            }
            return true; // Show non-restricted items for all users
          })
          .map((link, index) => (
            <Link href={link.link} className="text-white" key={index}>
              {link.title}
            </Link>
          ))}
      </div>
    </div>
  );
};

export default MenuBar;