import React, { useState } from 'react';

export default function LoginForm({ apiUrl, onSuccess, onError }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    if (!username.trim() || !password.trim()) {
      const msg = '请输入用户名和密码';
      setError(msg);
      onError?.({ message: msg });
      return;
    }

    setLoading(true);
    try {
      const res = await fetch(`${apiUrl}/api/user/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: username.trim(), password }),
        credentials: 'include',
      });
      const data = await res.json();

      if (data.success) {
        if (data.data?.require_2fa) {
          const msg = '此账户启用了两步验证，暂不支持通过 Widget 登录';
          setError(msg);
          onError?.({ message: msg });
          return;
        }
        onSuccess?.(data.data);
      } else {
        const msg = data.message || '登录失败';
        setError(msg);
        onError?.({ message: msg });
      }
    } catch (err) {
      const msg = '网络错误，请检查网络连接';
      setError(msg);
      onError?.({ message: msg });
    } finally {
      setLoading(false);
    }
  };

  return (
    <form className="naw-form" onSubmit={handleSubmit}>
      <div className="naw-field">
        <label className="naw-label">用户名或邮箱</label>
        <input
          className="naw-input"
          type="text"
          placeholder="请输入用户名或邮箱地址"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          autoComplete="username"
          disabled={loading}
        />
      </div>
      <div className="naw-field">
        <label className="naw-label">密码</label>
        <input
          className="naw-input"
          type="password"
          placeholder="请输入密码"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          autoComplete="current-password"
          disabled={loading}
        />
      </div>
      <p className="naw-error-msg">{error}</p>
      <button className="naw-button" type="submit" disabled={loading}>
        {loading ? '登录中...' : '登录'}
      </button>
    </form>
  );
}
