import { encryptPassword } from '../utils/cryptots';
import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams, Link, useLocation } from 'react-router-dom';
import { authService } from '../services/authService';
import { userApi } from '../services/userApi';
import { Mail, Lock, GraduationCap, AlertCircle, CheckCircle2, Phone } from 'lucide-react';
import { User, Loader2 } from '../icons/commonIcons';
import { BrandingContext } from '../App';

// 忘记密码弹窗（两步流程）
const ForgotPasswordModal: React.FC<{ onClose: () => void }> = ({ onClose }) => {
  const [step, setStep] = useState<'verify' | 'reset'>('verify')
  const [phone, setPhone] = useState('')
  const [code, setCode] = useState('')
  const [newPwd, setNewPwd] = useState('')
  const [confirmPwd, setConfirmPwd] = useState('')
  const [sending, setSending] = useState(false)
  const [countdown, setCountdown] = useState(0)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)

  useEffect(() => {
    if (countdown <= 0) return
    const t = setTimeout(() => setCountdown(c => c - 1), 1000)
    return () => clearTimeout(t)
  }, [countdown])

  const handleSend = async () => {
    if (!phone || phone.length !== 11) { setError('请输入正确的手机号'); return }
    setSending(true); setError('')
    try {
      await userApi.sendSmsCode(phone, 'reset_password')
      setCountdown(60)
    } catch (e: any) { setError(e.message || '发送失败') }
    finally { setSending(false) }
  }

  // 第一步：验证手机号+验证码
  const handleVerify = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!phone || !code) { setError('请填写手机号和验证码'); return }
    setLoading(true); setError('')
    try {
      await userApi.verifySmsCode(phone, code)
      setStep('reset')
    } catch (e: any) { setError(e.message || '验证失败') }
    finally { setLoading(false) }
  }

  // 第二步：设置新密码
  const handleReset = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newPwd || !confirmPwd) { setError('请填写新密码'); return }
    if (newPwd !== confirmPwd) { setError('两次密码不一致'); return }
    if (newPwd.length < 6) { setError('密码至少6位'); return }
    setLoading(true); setError('')
    try {
      await userApi.resetPasswordByPhone(phone, code, encryptPassword(newPwd))
      setSuccess(true)
    } catch (e: any) { setError(e.message || '修改失败') }
    finally { setLoading(false) }
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
        <h3 className="text-lg font-bold text-gray-900 mb-4">忘记密码</h3>

        {success ? (
          <div className="text-center py-6">
            <CheckCircle2 className="w-12 h-12 text-green-500 mx-auto mb-3" />
            <p className="text-gray-700 font-medium">密码修改成功</p>
            <button onClick={onClose} className="mt-4 px-6 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold hover:bg-blue-700">去登录</button>
          </div>
        ) : step === 'verify' ? (
          <form onSubmit={handleVerify} className="space-y-4">
            {error && <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">{error}</div>}
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-1">手机号</label>
              <input type="tel" value={phone} onChange={e => setPhone(e.target.value)} maxLength={11}
                placeholder="请输入注册时的手机号" autoComplete="off"
                className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500" required />
            </div>
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-1">验证码</label>
              <div className="flex gap-2">
                <input type="text" value={code} onChange={e => setCode(e.target.value)} maxLength={6}
                  placeholder="请输入验证码" autoComplete="one-time-code"
                  className="flex-1 px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500" required />
                <button type="button" onClick={handleSend} disabled={sending || countdown > 0}
                  className="px-4 py-3 bg-blue-600 text-white rounded-xl text-sm font-bold hover:bg-blue-700 disabled:opacity-50 whitespace-nowrap">
                  {sending ? '发送中...' : countdown > 0 ? `${countdown}s` : '获取验证码'}
                </button>
              </div>
            </div>
            <div className="flex gap-3 pt-2">
              <button type="button" onClick={onClose} className="flex-1 py-2.5 bg-gray-100 text-gray-700 rounded-xl font-medium hover:bg-gray-200">取消</button>
              <button type="submit" disabled={loading}
                className="flex-1 py-2.5 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 disabled:opacity-50">
                {loading ? '验证中...' : '下一步'}
              </button>
            </div>
          </form>
        ) : (
          <form onSubmit={handleReset} className="space-y-4">
            {error && <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">{error}</div>}
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-1">新密码</label>
              <input type="password" value={newPwd} onChange={e => setNewPwd(e.target.value)}
                placeholder="请输入新密码（至少6位）" autoComplete="new-password"
                className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500" required />
            </div>
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-1">确认新密码</label>
              <input type="password" value={confirmPwd} onChange={e => setConfirmPwd(e.target.value)}
                placeholder="请再次输入新密码" autoComplete="new-password"
                className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500" required />
            </div>
            <div className="flex gap-3 pt-2">
              <button type="button" onClick={() => { setStep('verify'); setError('') }}
                className="flex-1 py-2.5 bg-gray-100 text-gray-700 rounded-xl font-medium hover:bg-gray-200">上一步</button>
              <button type="submit" disabled={loading}
                className="flex-1 py-2.5 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2">
                {loading ? <><Loader2 className="w-4 h-4 animate-spin" />修改中...</> : '确认修改'}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  )
}

type LoginType = 'normal' | 'school' | 'phone';

interface LocationState {
  from?: {
    pathname: string;
  };
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const branding = React.useContext(BrandingContext);
  const [searchParams, setSearchParams] = useSearchParams();
  const [loginType, setLoginType] = useState<LoginType>('normal');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [schoolEmail, setSchoolEmail] = useState('');
  const [phoneNum, setPhoneNum] = useState('');
  const [smsCode, setSmsCode] = useState('');
  const [smsSending, setSmsSending] = useState(false);
  const [smsCountdown, setSmsCountdown] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [ssoLoading, setSsoLoading] = useState(false);
  const [forgotOpen, setForgotOpen] = useState(false);

  useEffect(() => {
    if (smsCountdown <= 0) return;
    const timer = setTimeout(() => setSmsCountdown(c => c - 1), 1000);
    return () => clearTimeout(timer);
  }, [smsCountdown]);

  const handleSendSms = async () => {
    if (!phoneNum || phoneNum.length !== 11) { setError('请输入正确的手机号'); return; }
    setSmsSending(true); setError(null);
    try {
      await userApi.sendSmsCode(phoneNum, 'login');
      setSmsCountdown(60);
    } catch (e: any) { setError(e.message || '发送失败'); }
    finally { setSmsSending(false); }
  };

  // 获取登录前想要访问的页面
  const from = (location.state as LocationState)?.from?.pathname || '/';

  // 检测SSO token并自动登录
  useEffect(() => {
    const ssoToken = searchParams.get('sso_token');
    if (ssoToken) {
      handleSSOLogin(ssoToken);
    }
  }, []);



  const handleSSOLogin = async (ssoToken: string) => {
    setSsoLoading(true);
    setError(null);

    try {
      const response = await authService.ssoLogin(ssoToken);
      if (response.code === 200) {
        // 登录成功，清除URL参数并跳转到原来想访问的页面
        setSearchParams({});
        navigate(from, { replace: true });
      } else {
        setError(response.message || 'SSO登录失败');
        // 清除无效的token参数
        setSearchParams({});
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'SSO登录失败，请稍后重试');
      setSearchParams({});
    } finally {
      setSsoLoading(false);
    }
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      if (loginType === 'phone') {
        // 手机号+验证码登录
        const apiResp = await userApi.loginByPhone(phoneNum, smsCode);
        authService.setToken(apiResp.access_token, {
          id: apiResp.user.id,
          nickname: apiResp.user.nickname,
          phone: apiResp.user.phone || undefined,
          email: apiResp.user.email || undefined,
          avatar: apiResp.user.avatar || undefined,
          registrationDate: apiResp.user.registration_date,
        });
        navigate(from, { replace: true });
        return;
      }

      const loginUsername = loginType === 'school' ? schoolEmail : username;
      const encryptedPassword = encryptPassword(password);
      const response = await authService.login(loginUsername, encryptedPassword);

      if (response.code === 200) {
        navigate(from, { replace: true });
      } else {
        setError(response.message || '登录失败，请检查账号密码');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '登录失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 via-white to-indigo-50 px-4">
      <div className="w-full max-w-md">
        <div className="bg-white rounded-2xl shadow-2xl border border-gray-100 p-8">
          {/* Logo/标题 */}
          <div className="text-center mb-8">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-2xl mb-4 overflow-hidden">
              {branding.system_logo
                ? <img src={branding.system_logo} alt="logo" className="w-full h-full object-contain" />
                : <GraduationCap className="w-8 h-8 text-white" />}
            </div>
            <h1 className="text-2xl font-bold text-gray-900 mb-2">欢迎登录{branding.system_name}</h1>
            <p className="text-sm text-gray-500">{branding.system_name} AI模型服务平台</p>
          </div>

          {/* SSO登录提示 */}
          {ssoLoading && (
            <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-xl flex items-center gap-3">
              <Loader2 className="w-5 h-5 text-blue-600 animate-spin flex-shrink-0" />
              <div className="flex-1">
                <p className="text-sm font-bold text-blue-900">正在通过学校账户一键登录...</p>
                <p className="text-xs text-blue-600 mt-1">请稍候，正在验证您的身份</p>
              </div>
            </div>
          )}

          {/* 登录方式切换 */}
          {!ssoLoading && (
            <div className="flex bg-gray-100 rounded-xl p-1 mb-6">
              <button type="button" onClick={() => { setLoginType('normal'); setError(null); }}
                className={`flex-1 py-2 px-2 rounded-lg text-sm font-bold transition-all ${loginType === 'normal' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}>
                <div className="flex items-center justify-center gap-1">
                  <User className="w-4 h-4" /><span>账号密码</span>
                </div>
              </button>
              <button type="button" onClick={() => { setLoginType('phone'); setError(null); }}
                className={`flex-1 py-2 px-2 rounded-lg text-sm font-bold transition-all ${loginType === 'phone' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}>
                <div className="flex items-center justify-center gap-1">
                  <Phone className="w-4 h-4" /><span>手机验证码</span>
                </div>
              </button>
            </div>
          )}

          {/* 错误提示 */}
          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2">
              <AlertCircle className="w-4 h-4 text-red-500 flex-shrink-0" />
              <p className="text-sm text-red-600">{error}</p>
            </div>
          )}

          {/* 登录表单 */}
          {!ssoLoading && (
            <form onSubmit={handleLogin} className="space-y-4">
            {loginType === 'phone' ? (
              <>
                <div>
                  <label className="block text-sm font-bold text-gray-700 mb-2">手机号</label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                    <input type="tel" value={phoneNum} onChange={(e) => setPhoneNum(e.target.value)}
                      placeholder="请输入手机号" maxLength={11}
                      className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all" required />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-bold text-gray-700 mb-2">验证码</label>
                  <div className="flex gap-2">
                    <input type="text" value={smsCode} onChange={(e) => setSmsCode(e.target.value)}
                      placeholder="请输入验证码" maxLength={6}
                      className="flex-1 px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all" required />
                    <button type="button" onClick={handleSendSms} disabled={smsSending || smsCountdown > 0}
                      className="px-4 py-3 bg-blue-600 text-white rounded-xl text-sm font-bold hover:bg-blue-700 disabled:opacity-50 whitespace-nowrap">
                      {smsSending ? '发送中...' : smsCountdown > 0 ? `${smsCountdown}s` : '获取验证码'}
                    </button>
                  </div>
                </div>
              </>
            ) : loginType === 'school' ? (
              <div>
                <label className="block text-sm font-bold text-gray-700 mb-2">学校邮箱 / 学号</label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input type="text" value={schoolEmail} onChange={(e) => setSchoolEmail(e.target.value)}
                    placeholder="请输入学校邮箱或学号"
                    className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all" required />
                </div>
                <p className="mt-1 text-xs text-gray-400">支持学校邮箱（如：student@university.edu）或学号登录</p>
              </div>
            ) : (
              <div>
                <label className="block text-sm font-bold text-gray-700 mb-2">用户名 / 手机号</label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input type="text" value={username} onChange={(e) => setUsername(e.target.value)}
                    placeholder="请输入用户名或手机号"
                    className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all" required />
                </div>
              </div>
            )}

            {loginType !== 'phone' && (
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-2">密码</label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
                  placeholder="请输入密码"
                  className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                  required />
              </div>
            </div>
            )}

            <div className="flex items-center justify-between text-sm">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <span className="text-gray-600">记住我</span>
              </label>
              <button
                type="button"
                onClick={() => setForgotOpen(true)}
                className="text-blue-600 hover:text-blue-700 font-medium"
              >
                忘记密码？
              </button>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-xl font-bold shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-indigo-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  <span>登录中...</span>
                </>
              ) : (
                <span>登录</span>
              )}
            </button>
          </form>
          )}

          {/* 其他登录方式 */}
          {!ssoLoading && (
          <div className="mt-6">
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-gray-200"></div>
              </div>
              <div className="relative flex justify-center text-xs">
                <span className="bg-white px-4 text-gray-400">或</span>
              </div>
            </div>
            <div className="mt-4 text-center">
              <p className="text-sm text-gray-600">
                还没有账号？{' '}
                <Link
                  to="/register"
                  className="text-blue-600 hover:text-blue-700 font-bold"
                >
                  立即注册
                </Link>
              </p>
            </div>
          </div>
          )}
        </div>

        {/* 底部说明 */}
        {!ssoLoading && (
          <div className="mt-6 text-center text-xs text-gray-400">
          </div>
        )}
      </div>
    </div>
    {forgotOpen && <ForgotPasswordModal onClose={() => setForgotOpen(false)} />}
    </>
  );
};

export default Login;

