import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useConfigStore } from '../stores/configStore'

export default function ServerSetupPage() {
  const navigate = useNavigate()
  const { setCustomServer, config, loading, error } = useConfigStore()
  const [serverUrl, setServerUrl] = useState('')
  const [manualMode, setManualMode] = useState(false)

  const handleAutoConnect = async () => {
    if (config && config.server_url) {
      navigate('/login')
    }
  }

  const handleManualConnect = async () => {
    if (!serverUrl.trim()) return
    
    let url = serverUrl.trim()
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      url = 'http://' + url
    }
    
    await setCustomServer(url)
    
    const { config: newConfig } = useConfigStore.getState()
    if (newConfig && newConfig.server_url) {
      navigate('/login')
    }
  }

  const hasEmbeddedConfig = config && config.server_url && config.server_url !== 'http://localhost:3000'

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="text-6xl mb-4">🎮</div>
          <h1 className="text-3xl font-bold text-white mb-2">FunMC</h1>
          <p className="text-gray-400">Minecraft 联机工具</p>
        </div>

        <div className="bg-gray-800/50 backdrop-blur rounded-2xl p-6 border border-gray-700/50">
          {hasEmbeddedConfig ? (
            <>
              <div className="text-center mb-6">
                <div className="inline-flex items-center gap-2 bg-green-500/20 text-green-400 px-4 py-2 rounded-full text-sm">
                  <span className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></span>
                  检测到预配置服务器
                </div>
              </div>
              
              <div className="bg-gray-700/50 rounded-xl p-4 mb-6">
                <p className="text-sm text-gray-400 mb-1">服务器名称</p>
                <p className="text-white font-medium">{config?.server_name || 'FunMC Server'}</p>
                <p className="text-sm text-gray-400 mt-3 mb-1">服务器地址</p>
                <p className="text-green-400 font-mono text-sm">{config?.server_url}</p>
              </div>

              <button
                onClick={handleAutoConnect}
                className="w-full py-3 bg-green-600 text-white rounded-xl font-medium hover:bg-green-700 transition-colors"
              >
                连接到此服务器
              </button>

              <button
                onClick={() => setManualMode(true)}
                className="w-full mt-3 py-3 bg-gray-700 text-gray-300 rounded-xl font-medium hover:bg-gray-600 transition-colors"
              >
                使用其他服务器
              </button>
            </>
          ) : manualMode || !hasEmbeddedConfig ? (
            <>
              <h2 className="text-lg font-semibold text-white mb-4 text-center">
                连接到服务器
              </h2>

              <div className="mb-6">
                <label className="block text-sm text-gray-400 mb-2">
                  服务器地址
                </label>
                <input
                  type="text"
                  value={serverUrl}
                  onChange={(e) => setServerUrl(e.target.value)}
                  placeholder="例如: funmc.com:3000 或 192.168.1.100:3000"
                  className="w-full px-4 py-3 bg-gray-700/50 border border-gray-600 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:border-green-500 transition-colors"
                  onKeyDown={(e) => e.key === 'Enter' && handleManualConnect()}
                />
                <p className="mt-2 text-xs text-gray-500">
                  输入管理员提供的服务器地址
                </p>
              </div>

              {error && (
                <div className="mb-4 p-3 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400 text-sm">
                  {error}
                </div>
              )}

              <button
                onClick={handleManualConnect}
                disabled={loading || !serverUrl.trim()}
                className="w-full py-3 bg-green-600 text-white rounded-xl font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? '连接中...' : '连接'}
              </button>

              {hasEmbeddedConfig && (
                <button
                  onClick={() => setManualMode(false)}
                  className="w-full mt-3 py-3 bg-gray-700 text-gray-300 rounded-xl font-medium hover:bg-gray-600 transition-colors"
                >
                  返回
                </button>
              )}
            </>
          ) : null}
        </div>

        <p className="text-center text-gray-500 text-xs mt-6">
          魔幻方开发
        </p>
      </div>
    </div>
  )
}
