"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { discordOAuth } from "@/lib/oauth/discord"
import { useLogin, useCurrentUser, useLogout } from "@/hooks/auth"
import { AppClient, ThirdType } from "@/services/auth/types"
import { tokenManager } from "@/lib/auth/token"
import { toast } from "sonner"

export default function TestDiscordPage() {
  const [logs, setLogs] = useState<string[]>([])
  const login = useLogin()
  const logout = useLogout()
  const { data: currentUser, isLoading, error } = useCurrentUser()

  const addLog = (message: string) => {
    const timestamp = new Date().toLocaleTimeString()
    setLogs(prev => [...prev, `[${timestamp}] ${message}`])
  }

  useEffect(() => {
    // 检查URL中是否有错误参数
    const urlParams = new URLSearchParams(window.location.search)
    const errorParam = urlParams.get('error')
    
    if (errorParam) {
      const errorMessages: Record<string, string> = {
        'discord_denied': 'Discord授权被用户拒绝',
        'discord_no_code': 'Discord授权码缺失',
        'discord_auth_failed': 'Discord认证失败',
        'discord_callback_error': 'Discord回调处理错误'
      }
      
      const errorMessage = errorMessages[errorParam] || `未知错误: ${errorParam}`
      addLog(`❌ ${errorMessage}`)
      toast.error("Discord login failed", { description: errorMessage })
    }
  }, [])

  const handleDiscordOAuthFlow = () => {
    addLog("🚀 开始Discord OAuth流程...")
    addLog("📋 新流程: 前端获取code -> 调用后端API")
    
    try {
      const state = Math.random().toString(36).substring(2, 15)
      const authUrl = discordOAuth.getAuthUrl(state)
      
      sessionStorage.setItem('discord_oauth_state', state)
      addLog(`📱 生成授权URL: ${authUrl}`)
      addLog("🔄 即将跳转到Discord授权页面...")
      addLog("💡 授权后将返回/login页面并自动处理登录")
      
      // 延迟跳转，让用户看到日志
      setTimeout(() => {
        window.location.href = authUrl
      }, 1000)
      
    } catch (error) {
      addLog(`❌ Discord OAuth流程失败: ${error}`)
      toast.error("Discord OAuth失败", { description: String(error) })
    }
  }

  const handleMockDiscordLogin = () => {
    addLog("🎭 开始Mock Discord登录...")
    
    try {
      const deviceId = tokenManager.getDeviceId()
      const loginData = {
        appClient: AppClient.Web,
        deviceCode: deviceId,
        thirdToken: "mock_discord_code_12345",
        thirdType: ThirdType.Discord
      }
      
      addLog(`📤 发送登录请求: ${JSON.stringify(loginData, null, 2)}`)
      login.mutate(loginData)
      
    } catch (error) {
      addLog(`❌ Mock登录失败: ${error}`)
      toast.error("Mock login failed", { description: String(error) })
    }
  }

  const handleLogout = () => {
    addLog("🚪 开始退出登录...")
    logout.mutate()
  }

  const clearLogs = () => {
    setLogs([])
  }

  const testEnvironmentVariables = () => {
    addLog("🔍 检查环境变量...")
    
    const discordClientId = process.env.NEXT_PUBLIC_DISCORD_CLIENT_ID
    const appUrl = process.env.NEXT_PUBLIC_APP_URL
    const mockEnabled = process.env.NEXT_PUBLIC_ENABLE_MOCK
    
    addLog(`NEXT_PUBLIC_DISCORD_CLIENT_ID: ${discordClientId ? '✅ 已设置' : '❌ 未设置'}`)
    addLog(`NEXT_PUBLIC_APP_URL: ${appUrl || 'http://localhost:3000 (默认)'}`)
    addLog(`NEXT_PUBLIC_ENABLE_MOCK: ${mockEnabled || 'false (默认)'}`)
    
    if (!discordClientId) {
      addLog("⚠️ Discord Client ID未配置，请检查环境变量")
      toast.warning("Missing configuration", { description: "Discord Client ID未配置" })
    }
  }

  useEffect(() => {
    if (login.isSuccess) {
      addLog("✅ 登录成功！")
      toast.success("Login successful")
    }
    if (login.error) {
      addLog(`❌ 登录失败: ${login.error.message}`)
    }
  }, [login.isSuccess, login.error])

  useEffect(() => {
    if (logout.isSuccess) {
      addLog("✅ 退出成功！")
      toast.success("Exit successfully")
    }
    if (logout.error) {
      addLog(`❌ 退出失败: ${logout.error.message}`)
    }
  }, [logout.isSuccess, logout.error])

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="text-center">
        <h1 className="text-3xl font-bold mb-2">Discord login test page</h1>
        <p className="text-gray-600">Testing Discord OAuth Login Function and Mock Interface Testing Discord OAuth Login Function and Mock Interface</p>
      </div>

      {/* 用户状态 */}
      <Card>
        <CardHeader>
          <CardTitle>user status</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <p>Loading...</p>
          ) : currentUser ? (
            <div className="space-y-2">
              <p><strong>User ID:</strong> {currentUser.userId}</p>
              <p><strong>Nickname:</strong> {currentUser.nickname}</p>
              <p><strong>Avatar:</strong> {currentUser.headImage || '无'}</p>
              <p><strong>Gender:</strong> {currentUser.sex === 1 ? '男' : currentUser.sex === 2 ? '女' : '未知'}</p>
              <p><strong>Birthday:</strong> {currentUser.birthday}</p>
              <p><strong>Need to improve information:</strong> {currentUser.cpUserInfo ? '是' : '否'}</p>
            </div>
          ) : (
            <p>Not logged in</p>
          )}
        </CardContent>
      </Card>

      {/* 操作按钮 */}
      <Card>
        <CardHeader>
          <CardTitle>test operation</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <Button onClick={testEnvironmentVariables} variant="secondary">
              🔍 检查环境变量
            </Button>
            <Button onClick={handleMockDiscordLogin} variant="tertiary">
              🎭 Mock Discord登录
            </Button>
            <Button onClick={handleDiscordOAuthFlow} className="col-span-2">
              🎮 真实Discord OAuth登录
            </Button>
            {currentUser && (
              <Button onClick={handleLogout} variant="secondary" className="col-span-2">
                🚪 退出登录
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 操作日志 */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>operation log</CardTitle>
          <Button onClick={clearLogs} variant="tertiary" size="small">
            clear log
                                </Button>
        </CardHeader>
        <CardContent>
          <div className="bg-gray-100 p-4 rounded-lg max-h-96 overflow-y-auto">
            {logs.length === 0 ? (
              <p className="text-gray-500">No log yet</p>
            ) : (
              <pre className="text-sm">
                {logs.map((log, index) => (
                  <div key={index} className="mb-1">
                    {log}
                  </div>
                ))}
              </pre>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 配置说明 */}
      <Card>
        <CardHeader>
          <CardTitle>configuration instructions</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4 text-sm">
            <div>
              <h4 className="font-semibold">New process description:</h4>
              <div className="bg-blue-50 p-3 rounded mt-2">
                <ol className="list-decimal list-inside space-y-1">
                  <li>Users click on Discord to log in</li>
                  <li>Go to the Discord license page</li>
                  <li>Discord回调到 /api/auth/discord/callback</li>
                  <li>Callback route gets code and redirects to /login? discord_code = xxx Callback route gets code and redirects to /login? discord_code = xxx</li>
                  <li>The front-end login page detects the code, and calls the back-end API to complete the login.</li>
                </ol>
              </div>
            </div>
            <div>
              <h4 className="font-semibold">Environment variables:</h4>
              <pre className="bg-gray-100 p-2 rounded mt-2">
{`NEXT_PUBLIC_DISCORD_CLIENT_ID=your_discord_client_id
DISCORD_CLIENT_SECRET=your_discord_client_secret  # 后端使用
NEXT_PUBLIC_APP_URL=http://localhost:3000
NEXT_PUBLIC_ENABLE_MOCK=true`}
              </pre>
            </div>
            <div>
              <h4 className="font-semibold">Discord回调URL:</h4>
              <p className="bg-gray-100 p-2 rounded mt-2">
                Http://localhost:3000/api/auth/discord/callback
                                            </p>
            </div>
            <div>
              <h4 className="font-semibold">API interface:</h4>
              <pre className="bg-gray-100 p-2 rounded mt-2">
{`POST /web/third/login
{
  "appClient": "WEB",
  "deviceCode": "设备ID", 
  "thirdToken": "discord_code",
  "thirdType": "DISCORD"
}`}
              </pre>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
} 