import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { login, register, isLoggedIn } from '../lib/api';
import AppShell from '../components/AppShell';
import { Icon } from '../components/icons';
import { useToast } from '../components/ToastProvider';

export default function Login() {
  const router = useRouter();
  const { showToast } = useToast();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (isLoggedIn()) {
      router.push('/');
    }
  }, [router]);

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

    try {
      await login(username, password);
      showToast('登录成功', { tone: 'success' });
      router.push('/');
    } catch (err) {
      setError(err.message);
      showToast(err.message, { tone: 'error' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <AppShell title="记账本" subtitle="随时记录每一笔收支" hideNav contentClassName="auth-layout" compactHeader>
      <div className="auth-page">
        <div className="auth-card auth-card--refresh">
          <div className="auth-logo auth-logo--refresh">
            <div className="auth-logo__mark" aria-hidden="true">
              <Icon name="chart" size={24} />
            </div>
            <h1>欢迎回来</h1>
            <p>登录后继续记录每一笔收支</p>
          </div>

          {error && <div className="error-msg">{error}</div>}

          <form onSubmit={handleSubmit} className="auth-form">
            <div className="form-group">
              <label htmlFor="username">用户名</label>
              <input
                id="username"
                type="text"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="3-20个字符"
                required
                disabled={loading}
              />
            </div>
            <div className="form-group">
              <label htmlFor="password">密码</label>
              <input
                id="password"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="6-20个字符"
                required
                disabled={loading}
              />
            </div>
            <button type="submit" className="btn btn-primary" disabled={loading}>
              {loading ? (
                <span className="button-content">
                  <Icon name="spinner" size={16} className="is-spinning" />
                  处理中...
                </span>
              ) : '登录'}
            </button>
          </form>
        </div>
      </div>
    </AppShell>
  );
}
