"use client";

import { useEffect, useState } from "react";
import { Button } from "@nextui-org/button";
import { BreadcrumbItem, Breadcrumbs } from "@nextui-org/react";
import { usePathname, useRouter } from "next/navigation";
import { Image } from "@nextui-org/react";
import { FormLayoutIcon } from "../icons";

export const Breadcrumb = () => {
  const [currentPage, setCurrentPage] = useState<React.Key>("");
  const router = useRouter();
  const pathname = usePathname();
  const pathnameSplit = pathname.split("/");
  pathnameSplit.shift();
  let pathnameTransformed = pathnameSplit.map((item) => {
    let words = item.split("-");
    let capitalizedWords = words.map(
      (word) => word.charAt(0).toUpperCase() + word.slice(1)
    );
    return capitalizedWords.join(" ");
  });

  console.log("pathname : ", pathnameTransformed);

  useEffect(() => {
    setCurrentPage(pathnameSplit[pathnameSplit.length - 1]);
  }, [pathnameSplit]);

  const handleAction = (key: any) => {
    const keyIndex = pathnameSplit.indexOf(key);
    const combinedPath = pathnameSplit.slice(0, keyIndex + 1).join("/");
    router.push("/" + combinedPath);
  };

  return (
    <div className="h-[100px] border-b-1 dark:border-b-1  dark:bg-black border-gray-300 dark:border-white">
      <div className="px-4 md:px-8">
        <div className="flex flex-row justify-between items-center py-3">
          <div className="">
            <p className="text-2xl font-semibold mb-2">
              {pathnameTransformed[pathnameTransformed.length - 1]}
            </p>
            <Breadcrumbs
              underline="active"
              onAction={(key) => handleAction(key)}
            >
              {pathnameTransformed?.map(
                (item, index) =>
                  item !== "Admin" && (
                    <BreadcrumbItem
                      key={pathnameSplit[index]}
                      isCurrent={pathnameSplit[index] === currentPage}
                    >
                      {item}
                    </BreadcrumbItem>
                  )
              )}
            </Breadcrumbs>
          </div>
          <FormLayoutIcon width={50} height={50} />
        </div>
      </div>
    </div>
  );
};
