import { useState, useRef, useEffect } from 'react';
import { verifyAdmin } from '../api';

interface TokenModalProps {
  onSuccess: () => void;
  onClose: () => void;
}

export default function TokenModal({ onSuccess, onClose }: TokenModalProps) {
  const [token, setToken] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token.trim()) return;
    setLoading(true);
    setError('');
    const ok = await verifyAdmin(token.trim());
    if (ok) {
      sessionStorage.setItem('admin_token', token.trim());
      onSuccess();
    } else {
      setError('Token 错误，请重试');
      setLoading(false);
    }
  };

  // Close on backdrop click
  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) onClose();
  };

  return (
    <div className="modal-backdrop" onClick={handleBackdropClick}>
      <div className="modal-card" role="dialog" aria-modal="true" aria-labelledby="modal-title">
        <p className="modal-title" id="modal-title">管理 Token</p>
        <form onSubmit={handleSubmit}>
          <input
            ref={inputRef}
            type="password"
            placeholder="管理 Token"
            value={token}
            onChange={e => setToken(e.target.value)}
            autoComplete="off"
          />
          {error && <p style={{ color: 'var(--text)', fontSize: '0.8rem', marginTop: '0.5rem' }}>{error}</p>}
          <div className="modal-actions">
            <button type="button" className="btn-ghost" onClick={onClose} disabled={loading}>
              取消
            </button>
            <button type="submit" className="btn-primary" disabled={loading || !token.trim()}>
              {loading ? '验证中…' : '确认'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
