// src/pages/Login.jsx
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from '../js/i18n';
import '../styles/Login.css';

const Login = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();

  // 新增：用户名密码登录相关状态
  const [username, setUsername] = useState('testuser');
  const [password, setPassword] = useState('testpass');
  const [loginLoading, setLoginLoading] = useState(false);
  const [loginError, setLoginError] = useState('');
  const [rememberMe, setRememberMe] = useState(false);


  // 新增：腾讯云开发用户名密码登录
  const handleCloudbaseLogin = async (e) => {
    e.preventDefault();
    setLoginError('');
    setLoginLoading(true);

    // 记住密码逻辑
    if (rememberMe) {
      localStorage.setItem('rememberedLogin', JSON.stringify({ username, password }));
    } else {
      localStorage.removeItem('rememberedLogin');
    }

    const app = cloudbase.init({
      env: 'xingzhi-authing-5gkb8pggc4cf2edf',
    });

    try {
      if (!app) {
        setLoginError('CloudBase SDK 未初始化');
        setLoginLoading(false);
        return;
      }
      // 0. 先进行匿名登录，避免 "you can't request without auth" 报错
      const auth = app.auth();
      await auth.signInAnonymously();
      // 1. 调用云函数 login 校验用户名密码，返回 ticket
      const res = await app.callFunction({
        name: 'login',
        data: {
          username,
          password,
        },
      });
      const { code } = res.result || {};
      if (code == 200) {
        localStorage.setItem('user', JSON.stringify({ username }));
        window.location.href = '/';
      } else {
        setLoginError('用户名或密码错误');
      }
    } catch (err) {
      setLoginError(err.message || '用户名或密码错误');
      setLoginLoading(false);
    }
  };

  // 记住密码功能：初始化时自动填充
  useEffect(() => {
    const saved = localStorage.getItem('rememberedLogin');
    if (saved) {
      try {
        const { username: savedUser, password: savedPass } = JSON.parse(saved);
        setUsername(savedUser || '');
        setPassword(savedPass || '');
        setRememberMe(true);
      } catch {}
    }
  }, []);

  return (
    <div className="login-container">
      <div className="login-card">
        <h1 className="login-title">{t('login')}</h1>
        <p className="login-subtitle">
          {t('loginSubtitle', '欢迎使用 AI 工具箱，请登录以获得完整体验')}
        </p>
        <div className="login-options">
          {/* 腾讯云开发用户名密码登录表单 */}
          <form className="cloudbase-login-form" onSubmit={handleCloudbaseLogin}>
            <input
              type="text"
              placeholder="用户名"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
              className="login-input enhanced-input"
              autoComplete="username"
            />
            <input
              type="password"
              placeholder="密码"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              className="login-input enhanced-input"
              autoComplete="current-password"
            />
            <label style={{ display: 'flex', alignItems: 'center', marginBottom: '0.5rem', fontSize: '0.98rem', color: '#6B7280', userSelect: 'none' }}>
              <input
                type="checkbox"
                checked={rememberMe}
                onChange={e => setRememberMe(e.target.checked)}
                style={{ marginRight: '8px', accentColor: '#6366f1' }}
              />
              记住密码
            </label>
            <button
              type="submit"
              className="login-btn enhanced-btn"
              disabled={loginLoading}
            >
              {loginLoading ? '登录中...' : '用户名密码登录'}
            </button>
            {loginError && <div className="login-error">{loginError}</div>}
          </form>
        </div>
      </div>
    </div>
  );
};

export default Login;
