import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/classMerge';
import { CircleSpinnerLoader } from '../loaders/CircleSpinnerLoader';

const buttonVariants = cva(
  'inline-flex items-center overflow-hidden justify-center gap-[5px] shadow-btn rounded transition-all duration-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none cursor-pointer disabled:cursor-not-allowed data-[loading=true]:cursor-progress',
  {
    variants: {
      buttonType: {
        default:
          'bg-white border hover:bg-item-hover disabled:bg-disabled disabled:text-gray-light active:bg-item-active data-[selected=true]:bg-item-select',
        black: 'bg-black text-white hover:bg-foreground-hover disabled:bg-foreground-hover',
        primary:
          'bg-primary text-white hover:bg-primary-light active:bg-primary-dark data-[selected=true]:bg-primary-dark',
        ghost:
          'bg-transparent text-gray-dark shadow-none hover:bg-item-hover hover:text-foreground disabled:bg-transparent disabled:text-gray-light active:bg-item-active data-[selected=true]:bg-item-select',
        link: 'bg-transparent text-gray-dark shadow-none hover:text-foreground disabled:bg-transparent disabled:text-gray-light'
      },
      size: {
        default: 'h-6',
        tall: 'h-7',
        small: 'h-[18px]'
      },
      iconButton: {
        true: '',
        false: 'px-2.5'
      },
      rounding: {
        default: 'rounded',
        full: 'rounded-full',
        large: 'rounded-lg',
        small: 'rounded-sm',
        none: 'rounded-none'
      }
    },
    compoundVariants: [
      {
        iconButton: true,
        size: 'default',
        className: 'w-6'
      },
      {
        iconButton: true,
        size: 'tall',
        className: 'w-7'
      },
      {
        iconButton: true,
        size: 'small',
        className: 'w-[18px]'
      }
    ],
    defaultVariants: {
      buttonType: 'default',
      size: 'default',
      iconButton: false
    }
  }
);

const iconVariants = cva('', {
  variants: {
    buttonType: {
      default: 'text-icon-color!',
      black: 'text-white!',
      primary: 'text-white!',
      ghost: 'text-icon-color!',
      link: 'text-icon-color!'
    },
    size: {
      default: 'text-icon-size',
      tall: 'text-icon-size-lg',
      small: 'text-icon-size-sm'
    }
  }
});

const loadingSizeVariants = {
  default: 'w-[var(--text-icon-size)] h-[var(--text-icon-size)]',
  tall: 'w-[var(--text-icon-size-lg)] h-[var(--text-icon-size-lg)]',
  small: 'w-[var(--text-icon-size-sm)] h-[var(--text-icon-size-sm)]'
};

export interface ButtonProps
  extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'prefix'>,
    VariantProps<typeof buttonVariants> {
  asChild?: boolean;
  prefix?: React.ReactNode;
  suffix?: React.ReactNode;
  loading?: boolean;
  selected?: boolean;
  prefixClassName?: string;
  suffixClassName?: string;
}

const AppButton = React.forwardRef<HTMLButtonElement, ButtonProps>(
  (
    {
      className = '',
      buttonType = 'default',
      size = 'default',
      asChild = false,
      prefix,
      suffix,
      children,
      loading = false,
      selected = false,
      disabled = false,
      prefixClassName,
      suffixClassName,
      rounding = 'default',
      ...props
    },
    ref
  ) => {
    const Comp = asChild ? Slot : 'button';
    const hasChildren = !!children;
    const iconButton = !hasChildren && (!prefix || !suffix);

    return (
      <Comp
        className={cn(buttonVariants({ buttonType, size, iconButton, rounding, className }))}
        ref={ref}
        disabled={disabled}
        data-loading={loading}
        data-selected={selected}
        {...props}>
        {loading ? (
          <LoadingIcon buttonType={buttonType} size={size} />
        ) : (
          prefix && (
            <span className={cn(iconVariants({ buttonType, size }), prefixClassName)}>
              {prefix}
            </span>
          )
        )}
        {hasChildren && <span className="text-base">{children}</span>}
        {suffix && (
          <span className={cn(iconVariants({ buttonType, size }), suffixClassName)}>{suffix}</span>
        )}
      </Comp>
    );
  }
);

AppButton.displayName = 'AppButton';

const LoadingIcon: React.FC<{
  buttonType: ButtonProps['buttonType'];
  size: ButtonProps['size'];
}> = ({ buttonType = 'default', size = 'default' }) => {
  return (
    <div
      className={cn(
        'flex items-center justify-center text-black dark:text-white',
        buttonType === 'black' && 'dark',
        loadingSizeVariants[size || 'default']
      )}>
      <CircleSpinnerLoader
        size={size === 'tall' ? 12.5 : 9.5}
        fill={
          buttonType === 'black'
            ? 'var(--color-white)'
            : buttonType === 'primary'
              ? 'var(--color-primary)'
              : 'var(--color-primary)'
        }
      />
    </div>
  );
};

export { AppButton, buttonVariants };
