import React from 'react';
import { cn } from '@/lib/utils';
import Wrapper from '@/components/common/Wrapper';
import { getFilteredIcons } from '@/components/icons/FaIcons';
import { getColor } from '@/utils/color';
import { ButtonProps } from '@/types/common';

const variantClasses = {
  solid: 'text-white hover:opacity-90',
  outline: 'bg-transparent hover:bg-opacity-10 border-2',
  ghost: 'bg-transparent hover:bg-opacity-10',
  link: 'bg-transparent hover:underline p-0',
};

export const Button = React.forwardRef<HTMLButtonElement | HTMLAnchorElement, ButtonProps>(
  (
    {
      text,
      href,
      variant = 'solid',
      className,
      icon,
      iconPosition = 'left',
      styling,
      openInNewTab = false,
      sectionId,
      ...props
    },
    ref
  ) => {
    const buttonClasses = cn(
      'inline-flex items-center justify-center font-medium rounded-md transition-colors p-2 px-4 builder',
      variantClasses[variant],
      className
    );

    const getButtonStyles = () => {
      const color = getColor(styling);

      if (variant === 'solid') {
        return {
          backgroundColor: color,
          color: 'white',
        };
      } else if (variant === 'outline') {
        return {
          borderColor: color,
          color: color,
        };
      } else if (variant === 'ghost' || variant === 'link') {
        return {
          color: color,
        };
      }
    };

    const content = (
      <>
        {icon && iconPosition === 'left' && <span className='mr-2'>{getFilteredIcons(icon)[icon]}</span>}
        {text}
        {icon && iconPosition === 'right' && <span className='ml-2'>{getFilteredIcons(icon)[icon]}</span>}
      </>
    );

    return (
      <Wrapper styling={styling} className='flex' id={sectionId}>
        <button
          ref={ref as React.Ref<HTMLButtonElement>}
          className={buttonClasses}
          style={getButtonStyles()}
          onClick={() => {
            if (href) {
              window.open(href, openInNewTab ? '_blank' : '_self');
            }
          }}
          {...props}
        >
          {content}
        </button>
      </Wrapper>
    );
  }
);

Button.displayName = 'Button';
