import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/auth';
import logoImg from '../assets/logo_128.png';
import styles from './AuthPage.module.css';

export function LoginPage() {
  const navigate = useNavigate();
  const login = useAuthStore((s) => s.login);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

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

    if (!username.trim()) { setError('请输入用户名或邮箱'); return; }
    if (password.length < 6) { setError('密码至少6位'); return; }

    setLoading(true);
    try {
      await login(username, password);
      navigate('/app', { replace: true });
    } catch (err: any) {
      const msg = err.response?.data?.message || err.response?.data?.error || '登录失败，请重试';
      setError(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.page}>
      <div className={styles.card}>
        <img src={logoImg} alt="AirDrama" width="64" height="64" style={{ marginBottom: '12px' }} />
        <h1 className={styles.title}>AirDrama</h1>
        <p className={styles.subtitle}>AI 视频生成平台</p>

        <form onSubmit={handleSubmit} className={styles.form}>
          <div className={styles.field}>
            <label className={styles.label}>用户名 / 邮箱</label>
            <input
              type="text"
              className={styles.input}
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="请输入用户名或邮箱"
              autoFocus
            />
          </div>

          <div className={styles.field}>
            <label className={styles.label}>密码</label>
            <input
              type="password"
              className={styles.input}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="请输入密码"
            />
          </div>

          {error && <div className={styles.error}>{error}</div>}

          <button type="submit" className={styles.submitBtn} disabled={loading}>
            {loading ? '登录中...' : '登录'}
          </button>
        </form>

        <p className={styles.switchLink}>
          如需注册请联系管理员
        </p>
      </div>
    </div>
  );
}
