import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { UserIcon } from '@heroicons/react/24/outline';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '@/client/mobile/hooks/AuthProvider';
import { authClient } from '@/client/api';
import WechatLoginButton from '@/client/components/WechatLoginButton';
import { toast } from 'sonner';

const AuthPage: React.FC = () => {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const [loading, setLoading] = useState(false);
  const { login } = useAuth();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  // 获取来源URL，优先使用URL参数，其次使用localStorage
  const getReturnUrl = () => {
    const urlParam = searchParams.get('returnUrl');
    if (urlParam) {
      return decodeURIComponent(urlParam);
    }
    return localStorage.getItem('mobile_return_url') || '/mobile';
  };

  const onSubmit = async (data: any) => {
    try {
      setLoading(true);
      
      // 首先尝试使用默认密码登录
      try {
        await login(data.username, '123456');
        // 登录成功后跳转回来源页
        const returnUrl = getReturnUrl();
        localStorage.removeItem('mobile_return_url'); // 清除保存的来源URL
        navigate(returnUrl, { replace: true });
        return; // 登录成功，直接返回
      } catch (loginError) {
        console.log('登录失败，尝试注册:', loginError);
        
        // 登录失败，尝试简单注册
        const response = await authClient.register.simple.$post({
          json: {
            username: data.username,
          }
        });
        
        if (response.status !== 201) {
          const result = await response.json();
          throw new Error(result.message || '注册失败');
        }
        
        const result = await response.json();
        
        // 注册成功后自动登录
        localStorage.setItem('token', result.token);
        await login(data.username, '123456'); // 使用默认密码登录
        
        // 跳转回来源页
        const returnUrl = getReturnUrl();
        localStorage.removeItem('mobile_return_url'); // 清除保存的来源URL
        navigate(returnUrl, { replace: true });
      }
    } catch (error) {
      console.error('Authentication error:', error);
      const errorMessage = (error as Error).message || '认证失败，请稍后重试';
      
      // 为用户禁用状态提供更友好的错误消息
      if (errorMessage.includes('disabled')) {
        toast.error('您的账号已被禁用，请联系管理员');
      } else {
        toast.error(errorMessage);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex justify-center items-center min-h-screen bg-gray-100">
      <div className="w-full max-w-md bg-white rounded-lg shadow-md overflow-hidden">
        <div className="p-6 sm:p-8">
          <div className="text-center mb-8">
            <h2 className="text-2xl font-bold text-gray-900">欢迎使用</h2>
            <p className="mt-2 text-sm text-gray-600">输入微信昵称即可开始使用</p>
          </div>
          
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            <div>
              <label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-1">
                微信昵称
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <UserIcon className="h-5 w-5 text-gray-400" />
                </div>
                <input
                  id="username"
                  type="text"
                  className={`w-full pl-10 pr-3 py-2 border ${errors.username ? 'border-red-300' : 'border-gray-300'} rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent`}
                  placeholder="输入微信昵称"
                  {...register('username', {
                    required: '微信昵称不能为空',
                    minLength: { value: 3, message: '微信昵称至少3个字符' },
                    maxLength: { value: 20, message: '微信昵称不能超过20个字符' }
                  })}
                />
              </div>
              {errors.username && (
                <p className="mt-1 text-sm text-red-600">{errors.username.message?.toString()}</p>
              )}
            </div>

            <div className="bg-blue-50 border border-blue-200 rounded-md p-3">
              <p className="text-sm text-blue-800">
                💡 智能认证：输入微信昵称后，系统会自动判断是登录还是注册。新用户将自动创建账号，默认密码为 <strong>123456</strong>
              </p>
            </div>
            
            <div>
              <button
                type="submit"
                disabled={loading}
                className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
              >
                {loading ? '处理中...' : '开始使用'}
              </button>
            </div>
          </form>
          
          <div className="mt-6">
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-gray-300"></div>
              </div>
              <div className="relative flex justify-center text-sm">
                <span className="px-2 bg-white text-gray-500">或使用以下方式登录</span>
              </div>
            </div>
            
            <div className="mt-4">
              <WechatLoginButton
                redirectUri={`${window.location.origin}/mobile/auth/callback`}
                onSuccess={(data) => {
                  localStorage.setItem('token', data.token);
                  const returnUrl = getReturnUrl();
                  localStorage.removeItem('mobile_return_url');
                  navigate(returnUrl, { replace: true });
                }}
                onError={(error) => {
                  toast.error(error.message);
                }}
                className="w-full"
              >
                微信一键登录
              </WechatLoginButton>
            </div>
            
            <div className="mt-4 text-center">
              <p className="text-sm text-gray-600">
                也可以输入微信昵称快速开始使用
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AuthPage;