"use client"
import { useSearchParams } from "next/navigation";
import { useAppSelector } from "@/core/utils/hooks/useRedux";
import { useCallback, useEffect, useRef } from "react";
import usePageParams from "@/app/(visualization)/project/@modals/(.)customization/_utils/hooks/usePageParams";
import useSelectedSurface from "@/app/(visualization)/project/@modals/(.)customization/_utils/hooks/useSelectedSurface";
import useGroutView from "@/app/(visualization)/project/@modals/(.)customization/_utils/hooks/useGroutView";
import usePattern from "@/app/(visualization)/project/@modals/(.)customization/_utils/hooks/usePattern";
import capitalize, { splitByCapitals } from "@/core/utils/helpers/capitalize";

import Link from "next/link";
import Image from "next/image";
import Back from "@/app/(visualization)/project/@modals/(.)customization/_components/_navigation/Back";
/**
 * Breadcrumbs are crucial point in navigation UX. In our case it will be collect **user's history stack**.
 * The history stack meaning **ordered** list of visited by user pages.
 * Current component has relation only to the **Customization** modal window, which implemented within parallel slot `modals`.
 */
export default function Breadcrumb(): JSX.Element {
  const container = useRef<HTMLDivElement>(null);
  const params = usePageParams();
  const sp = useSearchParams();
  const surface = useSelectedSurface();
  const patternSettings = usePattern();
  const grout = useGroutView();
  const detailedProduct = useAppSelector(state => state.customization.detailedObject);

  const narrower = grout || patternSettings;

  const isDetailsSegment = useCallback((segment: string, idx: number): boolean => idx === 2
    && !segment.toLowerCase().includes("own")
    && detailedProduct !== null, [detailedProduct]);

  const getBreadcrumbRoute = (segment: string, index: number): string => {
    const basePath = "/project/customization";
    const remainingSegments = params.segments?.slice(0, index + 1);
    const endPath = remainingSegments?.join("/");

    const newSearchParams = new URLSearchParams(sp);
    const newModalPath = basePath + "/" + endPath;

    newSearchParams.set("modal", newModalPath);
    newSearchParams.set("origin", sp.get("origin") as string);

    return newModalPath + "?" + newSearchParams.toString();
  }

  useEffect(() => {
    /** It's just to display always latest active element */
    if (container.current) {
      container.current.scroll({ left: 999999, behavior: "instant" });
    }
  }, [params.segments]);

  return (
    <div
      style={{ maxWidth: patternSettings? 410 : "" }}
      className={`
        h-[28px] flex items-center w-full max-w-[380px]  select-none
        ${patternSettings ? "!w-full" : ""} ${grout ? "!max-w-[290px]" : ""}
      `}
    >
      <Back />
      <div ref={container} className={"w-[calc(100%-20px)] overflow-x-auto scroll-bar-hidden"}>
        <div className={"w-max flex items-center text-[14px] font-normal text-grey-800"}>
          {surface && (
            <div className={"flex items-center hover:text-primary-500 transition-colors"}>
              {splitByCapitals(surface)}
              <div className="flex items-center justify-center w-[17px] h-[17px]">
                <Image src={"/icons/expand_more_right.svg"} alt={"expand_more_right"} width={4} height={8} />
              </div>
            </div>
          )}
          {params.segments?.map((s, index, array) => (
            <Link
              key={s}
              href={getBreadcrumbRoute( isDetailsSegment(s, index) ? detailedProduct!._id : s, index)}
              className={`
                flex items-center hover:text-primary-500 transition-colors
                ${params.segments?.at(-1) === s ? "text-primary-500" : ""}
                ${s === "own_texture" ? "!pointer-events-none" : ""} 
              `}
            >
              {isDetailsSegment(s, index)
                ? detailedProduct!.name
                : splitByCapitals(capitalize(decodeURIComponent(s).replace("_", " ")))}
              {index !== (array.length - 1) &&
                 (<div className="flex items-center justify-center w-[17px] h-[17px]">
                    <Image src={"/icons/expand_more_right.svg"} alt={"expand_more_right"} width={4} height={8} />
                  </div>)}
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}