import React, { useEffect, useState } from "react";
import { Home, NavigateNext } from "@mui/icons-material";
import style from "./breadcrumbs.module.css";
import { Breadcrumbs, Typography } from "@mui/material";
import { useRouter } from "next/router";
import Link from "next/link";

const BreadCrumbs = () => {
  const breadcrumbs = useBreadCrumbs();

  return (
    <Breadcrumbs aria-label="Breadcrumb">
      {breadcrumbs.map((item, index) =>
        index === breadcrumbs.length - 1 ? (
          <Typography key={index + 1} className={style.activeLink}>
            {item.name}
          </Typography>
        ) : (
          <Link className={style.parentLink} key={index + 1} href={item.path}>
            {item.name}
          </Link>
        )
      )}
    </Breadcrumbs>
  );
};

export default BreadCrumbs;

const useBreadCrumbs = () => {
  const router = useRouter();
  let breadcrumbs = [];
  const pathName = router.asPath.replace(/%20/g, " ");
  let spliteBreadCrumbs = pathName.split("/");
  console.log("spliteBreadCrumbs: ", spliteBreadCrumbs);
  let path = [];
  spliteBreadCrumbs.map((item, index) => {
    console.log("item; ", item);
    if (item == "" && index === 0) {
      console.log("true");
      breadcrumbs[index] = {
        path: "/",
        name: <Home />,
      };
    } else if (item != "") {
      const reformat = item.split("-");
      console.log("reformat: ", reformat);
      let newName = "";
      for (let childItem of reformat) {
        let newChild = childItem.split("_")[1] || childItem;
        newChild = [newChild.charAt(0).toUpperCase(), newChild.slice(1)].join(
          ""
        );
        newName = newName + " " + decodeURI(newChild);
      }
      path.push(item);

      breadcrumbs[index] = {
        path: "/" + path.join("/"),
        name: newName.split("?")[0],
      };
    }
  });

  return breadcrumbs;
};
