import React, { useEffect, useRef, useState } from 'react';
import { useAdmin } from '../context/AdminContext';
import './AdminTokenModal.css';

export default function AdminTokenModal() {
  const {
    tokenModalOpen,
    tokenSubmitError,
    submitToken,
    closeTokenModal,
  } = useAdmin();
  const [value, setValue] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    if (tokenModalOpen) {
      setValue('');
      requestAnimationFrame(() => inputRef.current?.focus());
    }
  }, [tokenModalOpen]);

  if (!tokenModalOpen) {
    return null;
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    submitToken(value.trim());
  };

  return (
    <div
      className="admin-token-backdrop"
      role="presentation"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) closeTokenModal();
      }}
    >
      <div
        className="admin-token-dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="admin-token-title"
      >
        <h2 id="admin-token-title" className="admin-token-title">
          管理员验证
        </h2>
        <p className="admin-token-hint">请输入访问令牌</p>
        <form onSubmit={handleSubmit}>
          <input
            ref={inputRef}
            type="password"
            className="admin-token-input"
            value={value}
            onChange={(e) => setValue(e.target.value)}
            placeholder="Token"
            autoComplete="off"
          />
          {tokenSubmitError && (
            <p className="admin-token-error" role="alert">
              {tokenSubmitError}
            </p>
          )}
          <div className="admin-token-actions">
            <button type="button" className="admin-token-btn secondary" onClick={closeTokenModal}>
              取消
            </button>
            <button type="submit" className="admin-token-btn primary">
              确定
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
