import { Button as TaroButton, ButtonProps as TaroButtonProps } from '@tarojs/components'
import { cn } from '@/utils/cn'
import { cva, type VariantProps } from 'class-variance-authority'
import { isH5 } from '@/utils/platform'
import { showToast } from '@tarojs/taro'

const buttonVariants = cva(
  'inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background mt-0',
  {
    variants: {
      variant: {
        default: 'bg-primary text-primary-foreground text-white hover:bg-primary/90',
        destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
        outline: 'border border-input hover:bg-accent hover:text-accent-foreground',
        secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
        ghost: 'hover:bg-accent hover:text-accent-foreground',
        link: 'underline-offset-4 hover:underline text-primary',
      },
      size: {
        default: 'h-10 py-2 px-4',
        sm: 'h-9 px-3 rounded-md text-xs',
        lg: 'h-11 px-8 rounded-md',
        icon: 'h-10 w-10',
      },
    },
    defaultVariants: {
      variant: 'default',
      size: 'default',
    },
  }
)

interface ButtonProps extends Omit<TaroButtonProps, 'size'>, VariantProps<typeof buttonVariants> {
  className?: string
  children?: React.ReactNode
}

export function Button({ className, variant, size, openType, onGetPhoneNumber, ...props }: ButtonProps) {
  // H5环境下的getPhoneNumber模拟
  const handleClick = (e: any) => {
    if (isH5() && openType === 'getPhoneNumber' && onGetPhoneNumber) {
      // 模拟获取手机号成功
      const mockEvent = {
        type: 'getphonenumber',
        timeStamp: Date.now(),
        target: {
          id: '',
          dataset: {}
        },
        currentTarget: {
          id: '',
          dataset: {}
        },
        detail: {
          errMsg: 'getPhoneNumber:ok',
          code: 'mock_code_for_h5_development'
        },
        mark: {}
      }
      onGetPhoneNumber(mockEvent as any)

      // 显示模拟成功的提示
      showToast({
        title: 'H5环境：手机号获取成功（模拟）',
        icon: 'success',
        duration: 2000
      })
      return
    }

    // 正常点击事件
    if (props.onClick) {
      props.onClick(e)
    }
  }

  return (
    <TaroButton
      className={cn(buttonVariants({ variant, size, className }))}
      openType={openType}
      onGetPhoneNumber={onGetPhoneNumber}
      onClick={handleClick}
      {...props}
    />
  )
}

// 预定义的按钮样式导出
export { buttonVariants }