import React from 'react';
import { Button } from '@/client/components/ui/button';
import { WechatFilled as Wechat } from '@ant-design/icons';
import { wechatAuthClient } from '@/client/api';
import { toast } from 'sonner';

interface WechatLoginButtonProps {
  redirectUri: string;
  scope?: 'snsapi_base' | 'snsapi_userinfo';
  onSuccess?: (data: any) => void;
  onError?: (error: Error) => void;
  children?: React.ReactNode;
  className?: string;
  variant?: 'default' | 'destructive' | 'outline' | 'secondary' | 'ghost' | 'link';
  size?: 'default' | 'sm' | 'lg' | 'icon';
}

const WechatLoginButton: React.FC<WechatLoginButtonProps> = ({
  redirectUri,
  scope = 'snsapi_userinfo',
  onSuccess,
  onError,
  children = '微信登录',
  className,
  variant = 'default',
  size = 'default'
}) => {
  const handleWechatLogin = async () => {
    try {
      // 使用RPC客户端获取微信授权URL
      const response = await wechatAuthClient.authorize.$post({
        json: { redirectUri, scope }
      });

      if (response.status !== 200) {
        const errorData = await response.json();
        throw new Error(errorData.message || '获取微信授权URL失败');
      }

      const { url } = await response.json();
      
      // 重定向到微信授权页面
      window.location.href = url;
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '微信登录失败';
      toast.error(errorMessage);
      onError?.(error as Error);
    }
  };

  return (
    <Button
      variant={variant}
      size={size}
      onClick={handleWechatLogin}
      className={`bg-[#07C160] text-white hover:bg-[#06B456] border-none ${className}`}
    >
      <Wechat className="w-4 h-4 mr-2" />
      {children}
    </Button>
  );
};

export default WechatLoginButton;