import { useState, useEffect } from 'react';
import { Settings, RefreshCw, Clock, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { maintenanceDetector } from '@/services/maintenanceDetector';

/**
 * 维护模式页面
 * 
 * 功能：
 * 1. 显示系统维护状态
 * 2. 后台自动检测服务恢复（静默）
 * 3. 支持手动重试连接
 */
const MaintenancePage = () => {
  const [checking, setChecking] = useState(false);
  const [lastCheckTime, setLastCheckTime] = useState<Date>(new Date());

  // 后台静默检测（每30秒一次，不打扰用户）
  useEffect(() => {
    const timer = setInterval(() => {
      setLastCheckTime(new Date());
      // 静默检测，不显示loading状态
      maintenanceDetector.checkRecovery();
    }, 30000); // 30秒检测一次

    return () => clearInterval(timer);
  }, []);

  // 手动检测服务器状态
  const handleManualCheck = async () => {
    setChecking(true);
    setLastCheckTime(new Date());

    try {
      const isRecovered = await maintenanceDetector.checkRecovery();
      
      if (!isRecovered) {
        console.log('服务尚未恢复，请稍后再试');
      }
      // 如果恢复了，maintenanceDetector 会自动跳转
    } catch (error) {
      console.error('检测服务恢复失败:', error);
    } finally {
      setChecking(false);
    }
  };

  // 获取维护开始时间（用于显示已维护时长）
  const getMaintenanceDuration = () => {
    const startTime = maintenanceDetector.getMaintenanceStartTime();
    if (!startTime) return '未知';

    const duration = Math.floor((Date.now() - startTime) / 1000 / 60);
    return duration < 1 ? '刚刚开始' : `${duration} 分钟`;
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      <div className="text-center p-8 max-w-2xl w-full mx-4">
        {/* 动画图标 */}
        <div className="mb-8 relative">
          <Settings
            className="w-20 h-20 mx-auto text-blue-500"
            style={{
              animation: 'spin 3s linear infinite',
            }}
          />
          <div className="absolute inset-0 flex items-center justify-center">
            <div
              className="w-28 h-28 border-4 border-blue-200 rounded-full opacity-20"
              style={{
                animation: 'ping 2s cubic-bezier(0, 0, 0.2, 1) infinite',
              }}
            />
          </div>
        </div>

        {/* 标题 */}
        <h1 className="text-5xl font-bold text-gray-800 mb-4">系统升级中</h1>

        <p className="text-gray-600 text-xl mb-3 leading-relaxed">
          系统暂时不可用，请稍后再试
        </p>

        <p className="text-sm text-gray-400 mb-12">
          可能原因：系统升级、服务器维护或临时故障
        </p>

        {/* 信息卡片 */}
        <div className="bg-white rounded-2xl p-8 shadow-xl backdrop-blur-sm bg-opacity-90 space-y-6">
          {/* 状态信息 */}
          <div className="flex items-center justify-center space-x-8 text-sm">
            <div className="flex items-center space-x-2 text-gray-600">
              <Clock className="w-4 h-4" />
              <span>已等待 {getMaintenanceDuration()}</span>
            </div>
            <div className="flex items-center space-x-2 text-gray-600">
              <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse" />
              <span>后台自动检测中</span>
            </div>
          </div>

          {/* 重试按钮 */}
          <Button
            onClick={handleManualCheck}
            disabled={checking}
            className="w-full h-12 text-lg"
            size="lg"
          >
            {checking ? (
              <>
                <RefreshCw className="mr-2 h-5 w-5 animate-spin" />
                检测中...
              </>
            ) : (
              <>
                <RefreshCw className="mr-2 h-5 w-5" />
                手动重试
              </>
            )}
          </Button>

          {/* 说明文字 */}
          <p className="text-xs text-gray-400">
            系统会自动检测服务恢复，恢复后将自动刷新页面
          </p>
        </div>

        {/* 提示信息 */}
        <div className="mt-8 bg-blue-50 rounded-xl p-6 border border-blue-100">
          <div className="flex items-start space-x-3">
            <AlertCircle className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" />
            <div className="text-left space-y-2 text-sm text-gray-600">
              <p className="font-medium text-gray-700">您可以：</p>
              <ul className="space-y-1 list-disc list-inside">
                <li>稍等片刻，页面会自动恢复</li>
                <li>点击"手动重试"按钮尝试重新连接</li>
                <li>如长时间未恢复，请联系系统管理员</li>
              </ul>
            </div>
          </div>
        </div>
      </div>

      {/* 添加动画样式 */}
      <style>{`
        @keyframes spin {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }

        @keyframes ping {
          75%, 100% {
            transform: scale(1.5);
            opacity: 0;
          }
        }
      `}</style>
    </div>
  );
};

export default MaintenancePage;
