import React, { useState, useEffect } from 'react';
import './PasswordProtection.css';
import { gradingApi } from '../api/grading';

interface PasswordProtectionProps {
  onPasswordCorrect: () => void;
}

const PasswordProtection: React.FC<PasswordProtectionProps> = ({ onPasswordCorrect }) => {
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  // 檢查是否已經有有效的密碼 session
  useEffect(() => {
    const savedPassword = sessionStorage.getItem('app_password_verified');
    if (savedPassword === 'true') {
      onPasswordCorrect();
    }
  }, [onPasswordCorrect]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!password.trim()) {
      setError('請輸入密碼');
      return;
    }

    setLoading(true);
    setError('');

    try {
      // 發送密碼驗證請求到後端
      const data = await gradingApi.verifyPassword(password);

      if (data.success) {
        // 密碼正確，保存到 sessionStorage
        sessionStorage.setItem('app_password_verified', 'true');
        onPasswordCorrect();
      } else {
        setError(data.message || '密碼錯誤，請重試');
      }
    } catch (err) {
      console.error('Password verification error:', err);
      setError('驗證失敗，請檢查網路連線');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="password-protection">
      <div className="password-container">
        <div className="password-header">
          <h1>🔒 AI 批改平台</h1>
          <p>請輸入存取密碼以繼續使用</p>
        </div>
        
        <form onSubmit={handleSubmit} className="password-form">
          <div className="password-input-group">
            <label htmlFor="password">存取密碼</label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="請輸入密碼"
              disabled={loading}
              autoFocus
            />
          </div>
          
          {error && (
            <div className="password-error">
              {error}
            </div>
          )}
          
          <button 
            type="submit" 
            className="password-submit"
            disabled={loading || !password.trim()}
          >
            {loading ? '驗證中...' : '進入平台'}
          </button>
        </form>
        
        <div className="password-footer">
          <p>
            <small>
              此平台需要密碼保護以確保使用安全性
              <br />
              如需協助，請聯絡管理員
            </small>
          </p>
        </div>
      </div>
    </div>
  );
};

export default PasswordProtection;