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 API_BASE = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:8010';


// ==================== 忘记密码弹窗 ====================
type ForgotVerifyType = 'phone' | 'email';

const ForgotPasswordModal: React.FC<{ onClose: () => void }> = ({ onClose }) => {
  const [verifyType, setVerifyType] = useState<ForgotVerifyType>('phone');
  const [step, setStep] = useState<'verify' | 'reset'>('verify');
  const [phone, setPhone] = useState('');
  const [smsCode, setSmsCode] = useState('');
  const [smsSending, setSmsSending] = useState(false);
  const [smsCountdown, setSmsCountdown] = useState(0);
  const [email, setEmail] = useState('');
  const [emailCode, setEmailCode] = useState('');
  const [emailSending, setEmailSending] = useState(false);
  const [emailCountdown, setEmailCountdown] = useState(0);
  const [newPwd, setNewPwd] = useState('');
  const [confirmPwd, setConfirmPwd] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

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

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

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

  const handleSendEmailCode = async () => {
    if (!email) { setError('请输入邮箱'); return; }
    setEmailSending(true); setError('');
    try {
      await userApi.sendEmailCode(email, 'reset_password');
      setEmailCountdown(60);
    } catch (e: any) { setError(e.message || '发送失败'); }
    finally { setEmailSending(false); }
  };

  const handleVerify = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true); setError('');
    try {
      if (verifyType === 'phone') {
        if (!phone || !smsCode) { setError('请填写手机号和验证码'); setLoading(false); return; }
        await userApi.verifySmsCode(phone, smsCode);
      } else {
        if (!email || !emailCode) { setError('请填写邮箱和验证码'); setLoading(false); return; }
        await userApi.verifyEmailCode(email, emailCode);
      }
      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 {
      const encrypted = encryptPassword(newPwd);
      if (verifyType === 'phone') {
        await userApi.resetPasswordByPhone(phone, smsCode, encrypted);
      } else {
        await userApi.resetPasswordByEmail(email, emailCode, encrypted);
      }
      setSuccess(true);
    } catch (e: any) { setError(e.message || '修改失败'); }
    finally { setLoading(false); }
  };

  const inputCls = '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';

  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' ? (
          <>
            <div className="flex bg-gray-100 rounded-xl p-1 mb-4">
              <button type="button" onClick={() => { setVerifyType('phone'); setError(''); }}
                className={`flex-1 py-2 rounded-lg text-sm font-bold transition-all ${verifyType === 'phone' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500'}`}>
                手机验证
              </button>
              <button type="button" onClick={() => { setVerifyType('email'); setError(''); }}
                className={`flex-1 py-2 rounded-lg text-sm font-bold transition-all ${verifyType === 'email' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500'}`}>
                邮箱验证
              </button>
            </div>
            <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>}
              {verifyType === 'phone' ? (
                <>
                  <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="请输入注册时的手机号" className={inputCls} 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={smsCode} onChange={e => setSmsCode(e.target.value)} maxLength={6}
                        placeholder="请输入验证码"
                        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={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>
                </>
              ) : (
                <>
                  <div>
                    <label className="block text-sm font-bold text-gray-700 mb-1">邮箱</label>
                    <input type="email" value={email} onChange={e => setEmail(e.target.value)}
                      placeholder="请输入绑定的邮箱" className={inputCls} 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={emailCode} onChange={e => setEmailCode(e.target.value)} maxLength={6}
                        placeholder="请输入验证码"
                        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={handleSendEmailCode} disabled={emailSending || emailCountdown > 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">
                        {emailSending ? '发送中...' : emailCountdown > 0 ? `${emailCountdown}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位）" className={inputCls} 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="请再次输入新密码" className={inputCls} 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' | '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 [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [phoneNum, setPhoneNum] = useState('');
  const [smsCode, setSmsCode] = useState('');
  const [smsSending, setSmsSending] = useState(false);
  const [smsCountdown, setSmsCountdown] = useState(0);
  const [loginType, setLoginType] = useState<LoginType>('normal');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [ssoLoading, setSsoLoading] = useState(false);
  const [forgotOpen, setForgotOpen] = useState(false);

  const from = (location.state as LocationState)?.from?.pathname || '/';

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

  const handleSSOLogin = async (ssoToken: string) => {
    setSsoLoading(true); setError(null);
    try {
      const response = await authService.ssoLogin(ssoToken);
      if (response.code === 200) {
        setSearchParams({});
        navigate(from, { replace: true });
      } else {
        setError(response.message || 'SSO登录失败');
        setSearchParams({});
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'SSO登录失败，请稍后重试');
      setSearchParams({});
    } finally { setSsoLoading(false); }
  };

  useEffect(() => {
    const ssoToken = searchParams.get('sso_token');
    if (ssoToken) handleSSOLogin(ssoToken);
  }, []);

  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 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 encryptedPassword = encryptPassword(password);
      const response = await authService.login(username, encryptedPassword);
      if (response.code === 200) {
        navigate(from, { replace: true });
      } else {
        setError(response.message || '登录失败，请检查账号密码');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '登录失败，请稍后重试');
    } finally { setLoading(false); }
  };

  const tabCls = (active: boolean) =>
    `flex-1 py-2 px-1 rounded-lg text-sm font-bold transition-all ${active ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`;

  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">
          <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>

          {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={tabCls(loginType === 'normal')}>
                <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={tabCls(loginType === 'phone')}>
                <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 === 'normal' && (
                <>
                  <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>
                  <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">
                {loginType === 'normal' && (
                  <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>
                )}
                <div className={loginType !== 'normal' ? 'ml-auto' : ''}>
                  <button type="button" onClick={() => setForgotOpen(true)}
                    className="text-blue-600 hover:text-blue-700 font-medium">
                    忘记密码？
                  </button>
                </div>
              </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>

              {/* 统一身份认证登录 */}
              <button
                type="button"
                onClick={async () => {
                  try {
                    const resp = await fetch(`${API_BASE}/api/sso/config`);
                    const data = await resp.json();
                    if (data.sso_enabled && data.authorize_url) {
                      window.location.href = data.authorize_url;
                    } else {
                      setError('统一身份认证未启用，请联系管理员');
                    }
                  } catch {
                    setError('无法连接认证服务');
                  }
                }}
                className="mt-4 w-full py-3 bg-white border-2 border-blue-100 text-blue-700 rounded-xl font-bold hover:bg-blue-50 hover:border-blue-200 transition-all flex items-center justify-center gap-2"
              >
                <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                </svg>
                统一身份认证登录
              </button>

              <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>
        <div className="mt-6 flex flex-col items-center gap-1 text-xs text-gray-400">
          <p>© 2026 {branding.system_name}</p>
          <div className="flex items-center justify-center gap-4">
            <a
              href="https://beian.mps.gov.cn/#/query/webSearch?code=51019002009294"
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-1 hover:text-gray-600"
            >
              <img src="https://beian.mps.gov.cn/web/assets/logo01.6189a29f.png" alt="公安备案图标" className="h-4 w-4" />
              川公网安备51019002009294号
            </a>
            <a
              href="https://beian.miit.gov.cn/"
              target="_blank"
              rel="noopener noreferrer"
              className="hover:text-gray-600"
            >
              蜀ICP备2025168675号-3
            </a>
          </div>
        </div>
      </div>
    </div>
    {forgotOpen && <ForgotPasswordModal onClose={() => setForgotOpen(false)} />}
    </>
  );
};

export default Login;
