import { useState, useCallback } from 'react';
import { useAuthStore } from '../store/auth';
import logoImg from '../assets/logo_32.png';
import styles from './LoginModal.module.css';

interface Props {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

export function LoginModal({ isOpen, onClose, onSuccess }: Props) {
  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 = useCallback(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);
      onSuccess();
    } catch (err: any) {
      const msg = err.response?.data?.message || err.response?.data?.error || '登录失败，请重试';
      setError(msg);
    } finally {
      setLoading(false);
    }
  }, [username, password, login, onSuccess]);

  if (!isOpen) return null;

  return (
    <div className={styles.overlay}
      onMouseDown={(e) => { if (e.target === e.currentTarget) (e.currentTarget as HTMLElement).dataset.mouseDownOnOverlay = 'true'; }}
      onMouseUp={(e) => {
        if ((e.currentTarget as HTMLElement).dataset.mouseDownOnOverlay === 'true' && e.target === e.currentTarget) onClose();
        (e.currentTarget as HTMLElement).dataset.mouseDownOnOverlay = '';
      }}
    >
      <div className={styles.panel}>
        <button className={styles.closeBtn} onClick={onClose} aria-label="关闭">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M18 6L6 18M6 6l12 12" />
          </svg>
        </button>

        <div className={styles.header}>
          <img src={logoImg} alt="" className={styles.headerLogo} />
          <span className={styles.headerTitle}>Air Drama</span>
        </div>

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

          <p className={styles.hint}>目前仅限受邀创作者体验</p>
        </form>
      </div>
    </div>
  );
}
