// eslint-disable-next-line import/no-extraneous-dependencies
import { useNavigate } from 'react-router-dom';
import React from 'react';

interface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
  to: string;
  children: React.ReactNode;
  replace?: boolean; // 是否替换当前历史记录
  target?: string; // 打开方式
  outLink?: boolean;
}

export default function Link({
  to,
  children,
  onClick,
  replace = false,
  target = undefined,
  outLink = false,
  ...props
}: LinkProps) {
  const navigate = useNavigate();

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    const isInternal = to.startsWith('/') || to.startsWith('#') || to.startsWith('?');
    if (!outLink && isInternal) {
      e.preventDefault();
      navigate(to, { replace });
    } else if (!target) {
      e.preventDefault();
      window.location.href = to;
    }
    e.preventDefault();
    onClick?.(e);
  };

  return (
    <a href={to} onClick={handleClick} target={target} rel="noreferrer" {...props}>
      {children}
    </a>
  );
}
