import { Transition } from "@headlessui/react";
import classNames from "classnames";
import React from "react";
import {
  NavLinkProps,
  useHref,
  useLinkClickHandler,
  useMatch,
  useResolvedPath,
} from "react-router-dom";

type Props = {
  caption: React.ReactNode;
  icon?: React.ReactNode;
  collapsed?: boolean;
} & NavLinkProps;

export default function SideNavItem({
  caption,
  to,
  icon,
  replace,
  state,
  target,
  onClick,
  reloadDocument,
  collapsed,
}: Props) {
  let internalOnClick = useLinkClickHandler(to, {
    replace,
    state,
    target,
  });

  const href = useHref(to);
  const resolved = useResolvedPath(to);
  const match = useMatch({ path: resolved.pathname, end: true });

  function handleClick(event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) {
    if (onClick) onClick(event);

    if (!event.defaultPrevented && !reloadDocument) {
      internalOnClick(event);
    }
  }

  return (
    <a
      href={href}
      className={classNames(
        "relative flex flex-row items-center justify-center p-2 py-4",
        "rounded-md hover:bg-gray-300/5 transition-colors",
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/20",
        { "bg-gray-300/5": match }
      )}
      onClick={handleClick}
    >
      {icon && <div className="flex-none w-6 h-6">{icon}</div>}
      <Transition
        as="div"
        appear={true}
        className="flex-1 font-medium text-base leading-4 ml-5"
        show={!collapsed}
        enter="transition duration-100"
        enterFrom="opacity-0"
        enterTo="opacity-100"
        leave="transition duration-100"
        leaveFrom="opacity-100"
        leaveTo="opacity-100"
      >
        {caption}
      </Transition>
    </a>
  );
}
