import { resolveHref } from '@/lib/parseTextFormats';
import React, { useState } from 'react';

interface LinkButtonProps {
  href: string;
  displayText: string;
  isLoading?: boolean;
  loadingText?: string;
}

const LinkButton: React.FC<LinkButtonProps> = ({
  href,
  displayText,
  isLoading = false,
  loadingText = '',
}) => {
  const [internalIsLoading, setInternalIsLoading] = useState(isLoading);
  const [internalLoadingText, setInternalLoadingText] = useState(loadingText);

  const { href: resolvedHref, isExternal } = resolveHref(href);
  const targetAttrs = isExternal ? { target: '_blank', rel: 'noopener noreferrer' } : undefined;

  const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
    if (internalIsLoading) {
      event.preventDefault();
      return;
    }

    event.preventDefault();
    setInternalIsLoading(true);
    setInternalLoadingText('Searching stores that sell deodeok');

    setTimeout(() => {
      setInternalIsLoading(false);
      setInternalLoadingText('');
      window.open(resolvedHref, '_blank', 'noopener noreferrer');
    }, 3000);
  };

  return (
    <a
      className="bogam-link-button"
      href={resolvedHref}
      onClick={handleClick}
      aria-disabled={internalIsLoading}
      {...targetAttrs}
    >
      {internalIsLoading ? internalLoadingText : displayText}
    </a>
  );
};

export default LinkButton;
