import React, { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '@/client/mobile/hooks/AuthProvider';
import { wechatAuthClient } from '@/client/api';
import { toast } from 'sonner';

const WechatCallbackPage: React.FC = () => {
  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading');
  const [message, setMessage] = useState<string>('处理中...');
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { loginWithToken } = useAuth();

  useEffect(() => {
    const handleWechatCallback = async () => {
      try {
        const code = searchParams.get('code');
        const state = searchParams.get('state');
        
        if (!code) {
          throw new Error('微信授权失败：未获取到授权码');
        }

        // 使用微信授权码进行登录
        const response = await wechatAuthClient.login.$post({
          json: { code }
        });

        if (response.status !== 200) {
          const errorData = await response.json();
          throw new Error(errorData.message || '微信登录失败');
        }

        const result = await response.json();
        
        // 使用token登录（复用封装逻辑）
        await loginWithToken(result.token, result.user);
        
        setStatus('success');
        setMessage('微信登录成功！');
        
        // 跳转回来源页
        const returnUrl = localStorage.getItem('mobile_return_url') || '/mobile';
        localStorage.removeItem('mobile_return_url');
        
        setTimeout(() => {
          navigate(returnUrl, { replace: true });
        }, 1500);
        
      } catch (error) {
        console.error('微信回调处理失败:', error);
        setStatus('error');
        setMessage(error instanceof Error ? error.message : '微信登录失败');
        
        toast.error('微信登录失败，请重试');
        
        setTimeout(() => {
          navigate('/mobile/login', { replace: true });
        }, 3000);
      }
    };

    handleWechatCallback();
  }, []);

  const getStatusIcon = () => {
    switch (status) {
      case 'loading':
        return (
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        );
      case 'success':
        return (
          <div className="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
            <svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
        );
      case 'error':
        return (
          <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
            <svg className="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
        );
    }
  };

  return (
    <div className="flex justify-center items-center min-h-screen bg-gray-100">
      <div className="flex flex-col items-center">
        {getStatusIcon()}
        <h2 className="mt-4 text-lg font-medium text-gray-900">
          {status === 'loading' && '微信登录处理中...'}
          {status === 'success' && '登录成功！'}
          {status === 'error' && '登录失败'}
        </h2>
        <p className="mt-2 text-sm text-gray-600">{message}</p>
        {status === 'loading' && (
          <p className="mt-2 text-xs text-gray-500">请稍候，正在处理微信授权...</p>
        )}
      </div>
    </div>
  );
};

export default WechatCallbackPage;