import { FC, isValidElement, ReactNode } from 'react';
import { Params, useMatches } from 'react-router';
import { twx } from '../utils';
import { Group } from '.';

export type BreadcrumbsProps = {
  label?: string;
  crumbClassName?: string;
};

export const Breadcrumbs: FC<BreadcrumbsProps> = ({
  label,
  crumbClassName,
}) => {
  const matches = useMatches() as {
    id: string;
    pathname: string;
    params: Params<string>;
    data: unknown;
    handle: { crumb: () => ReactNode };
  }[];

  const matchesCrumbs = matches
    .filter((match) => Boolean(match.handle?.crumb))
    .map((match) => {
      return match.handle.crumb();
    });

  const crumbs = matchesCrumbs.slice(0, -1);
  const lastCrumb = matchesCrumbs.pop();

  return (
    <Group className="gap-1 text-xl font-bold">
      {crumbs.map((crumb, i) => {
        return (
          <Group
            key={i}
            className={twx('text-black/40 dark:text-white/40', crumbClassName)}
          >
            {crumb} <p className="px-1">/</p>
          </Group>
        );
      })}
      <div className={crumbClassName}>
        {isValidElement(lastCrumb)
          ? (lastCrumb?.props as { children: ReactNode }).children
          : lastCrumb}
      </div>
      {label ? (
        <>
          <p className="text-black dark:text-white/40">/</p>
          <div>{label}</div>
        </>
      ) : null}
    </Group>
  );
};

export default Breadcrumbs;
