import { type FC, type ReactNode } from 'react';

import type { ClickableProps } from '../Clickable';

import { useAppRouter } from '~/src/lib/router2';
import Clickable from '../Clickable';

type BackButtonProps = {
  href?: string;
  children: ReactNode;
};

const BackButton: FC<BackButtonProps> = ({ children, href }) => {
  const router = useAppRouter();

  const canGoBack = router.canGoBack() || href;
  if (!canGoBack) return null;

  const props: Omit<ClickableProps, 'children'> = {
    href: undefined,
    onClick: undefined,
  };

  if (href) props.href = href;
  else props.onClick = () => router.back();

  return (
    <Clickable {...props} testId="backButton">
      {children}
    </Clickable>
  );
};

export default BackButton;
