import Link from 'next/link';
import { Icon } from '@iconify/react';

import { cn } from '@/lib/helper';

interface MenuItemProps {
  title: string;
  href?: string;
  icon?: string;
  active?: boolean;
  isLoading?: boolean;
  onClick?: () => void;
  className?: string;
}

const MenuItem = ({
  title,
  href,
  icon,
  active = false,
  isLoading = false,
  className,
  onClick,
}: MenuItemProps) => {
  const menuItemBaseClassName = cn(
    'group px-3 py-2 text-base text-black font-semibold flex flex-row items-center rounded-md',
    { 'bg-gray-100 border-l-2 border-l-primary': active },
    className
  );

  const menuItemContent = (
    <>
      {icon && (
        <Icon
          icon={icon}
          width={20}
          height={20}
          className={cn('group-active:text-[inherit]', {
            'text-gray-400': !active,
            'text-black': active,
          })}
        />
      )}

      <span
        className={cn({ 'opacity-40': !active }, 'group-active:opacity-100')}
      >
        {title}
      </span>
    </>
  );

  return (
    <li>
      {!isLoading && href && (
        <Link href={href} className={menuItemBaseClassName}>
          {menuItemContent}
        </Link>
      )}

      {!isLoading && !href && (
        <button className={menuItemBaseClassName} onClick={onClick}>
          {menuItemContent}
        </button>
      )}

      {isLoading && (
        <button className={menuItemBaseClassName}>
          <span
            className={cn('loading loading-dots loading-md mx-auto', {
              'text-gray-400': !active,
              'text-black': active,
            })}
          />
        </button>
      )}
    </li>
  );
};

export default MenuItem;
