'use client';

import React from 'react';

import { MdOpenInNew } from 'react-icons/md';

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

type Theme = 'gray' | 'blue' | 'yellow';
type Size = 'small' | 'medium' | 'large';

type BaseProps = {
  children: React.ReactNode;
  className?: string;
  theme?: Theme;
  size?: Size;
  icon?: React.ReactNode;
  external?: boolean;
  targetBlank?: boolean;
};

type AnchorProps = BaseProps &
  Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'className'> & {
    href: string;
    external?: boolean; // New prop for external links
    targetBlank?: boolean; // New prop for opening links in a new tab
  };

type NativeButtonProps = BaseProps &
  Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'className'> & {
    href?: undefined;
  };

export type ButtonProps = (AnchorProps & { targetBlank?: boolean }) | NativeButtonProps;

const baseClasses =
  'inline-flex items-center justify-center gap-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2';

const themeClasses: Record<Theme, string> = {
  blue: 'bg-mma-blue text-white hover:bg-mma-blue/90 focus-visible:ring-mma-blue',
  gray: 'bg-neutral-200 text-mma-blue hover:bg-mma-yellow',
  yellow: 'bg-mma-yellow text-mma-blue hover:bg-mma-yellow/90',
};

const sizeClasses: Record<Size, string> = {
  small: 'px-2 py-1 text-sm font-medium',
  medium: 'px-4 py-2 text-[16px] font-medium',
  large: 'px-6 py-3 text-lg',
};

const Button = (props: ButtonProps) => {
  const {
    children,
    className,
    theme = 'gray',
    size = 'medium',
    icon,
    external,
    targetBlank,
    ...rest
  } = props;

  const classes = cn(baseClasses, themeClasses[theme as Theme], sizeClasses[size], className);

  if ('href' in props && props.href) {
    // Anchor button
    return (
      <a
        {...(rest as React.AnchorHTMLAttributes<HTMLAnchorElement>)}
        className={classes}
        target={external || targetBlank ? '_blank' : undefined} // Add target for external or targetBlank links
        rel={external ? 'noopener noreferrer' : undefined} // Add rel for external links
      >
        {icon && !external && <span className="mr-2">{icon}</span>}{' '}
        {/* Render icon if not external */}
        {children}
        {external && <MdOpenInNew />} {/* Add external icon */}
      </a>
    );
  }

  // Native button
  const buttonProps = rest as React.ButtonHTMLAttributes<HTMLButtonElement>;
  return (
    <button {...buttonProps} className={classes} type={buttonProps.type ?? 'button'}>
      {icon && <span className="mr-2">{icon}</span>} {/* Render icon if provided */}
      {children}
    </button>
  );
};

export default Button;
