import type { ReactElement, ButtonHTMLAttributes } from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
import { useAppSelector } from '@/hooks/redux-hooks';

const primaryButtonVariants = cva(
  'inline-flex items-center justify-center px-3 py-1.5 rounded text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer',
  {
    variants: {
      size: {
        default: 'h-10',
        small: 'h-8',
        large: 'h-12',
      },
      variant: {
        default: 'bg-[#112868] text-[#23dce1] hover:bg-[#23dce1] hover:text-[#112868]',
        disabled: 'bg-[#112868] text-[#23dce1] opacity-50',
      },
    },
    defaultVariants: {
      size: 'default',
      variant: 'default',
    },
  }
);

interface PrimaryButtonProps
  extends ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof primaryButtonVariants> {
  children: React.ReactNode;
}

export const PrimaryButton = ({
  children,
  size,
  variant,
  className,
  disabled,
  ...props
}: PrimaryButtonProps): ReactElement => {
  const buttonVariant = disabled ? 'disabled' : variant || 'default';
  const { theme } = useAppSelector((state) => state.theme);
  const { roles } = useAppSelector((state) => state.auth);

  // Check if user is tenant admin (not super_admin) or if we're on a tenant route
  let rolesArray: string[] = [];
  if (Array.isArray(roles)) {
    rolesArray = roles;
  } else if (typeof roles === 'string') {
    try {
      rolesArray = JSON.parse(roles);
    } catch {
      rolesArray = [];
    }
  }
  const isSuperAdmin = rolesArray.includes('super_admin');
  const isTenantAdmin = !isSuperAdmin && rolesArray.length > 0;
  
  // Check if we're on a tenant route (for login page where user might not be authenticated)
  // Use /tenant/ or exactly /tenant to avoid matching /tenants page
  const isTenantRoute = typeof window !== 'undefined' && (window.location.pathname.startsWith('/tenant/') || window.location.pathname === '/tenant');
  
  // Use theme colors for tenant admin or tenant routes, default colors for super admin
  const shouldUseTheme = (isTenantAdmin || (isTenantRoute && !isSuperAdmin)) && theme;
  const primaryColor = shouldUseTheme && theme.primary_color ? theme.primary_color : '#112868';
  const secondaryColor = shouldUseTheme && theme.secondary_color ? theme.secondary_color : '#23dce1';

  return (
    <button
      className={cn(primaryButtonVariants({ size, variant: buttonVariant }), className)}
      style={
        buttonVariant === 'default'
          ? {
              backgroundColor: primaryColor,
              color: secondaryColor,
            }
          : buttonVariant === 'disabled'
          ? {
              backgroundColor: primaryColor,
              color: secondaryColor,
              opacity: 0.5,
            }
          : undefined
      }
      onMouseEnter={(e) => {
        if (buttonVariant === 'default' && !disabled) {
          e.currentTarget.style.backgroundColor = secondaryColor;
          e.currentTarget.style.color = primaryColor;
        }
      }}
      onMouseLeave={(e) => {
        if (buttonVariant === 'default' && !disabled) {
          e.currentTarget.style.backgroundColor = primaryColor;
          e.currentTarget.style.color = secondaryColor;
        }
      }}
      disabled={disabled}
      {...props}
    >
      {children}
    </button>
  );
};
