import { useState } from 'react';
import {
  register,
  login,
  listClusters,
  createCluster,
  setAuthToken,
  type RegisterBody,
  type LoginBody,
  type CreateClusterRequest,
} from '@/api';

export function ApiTest() {
  const [result, setResult] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [token, setToken] = useState<string>('');

  const addLog = (message: string) => {
    setResult((prev) => prev + '\n' + message);
    console.log(message);
  };

  const clearLog = () => {
    setResult('');
  };

  const handleRegister = async () => {
    setLoading(true);
    clearLog();
    try {
      addLog('📝 测试注册...');
      const request: RegisterBody = {
        username: 'testuser',
        password: 'password123',
      };
      
      addLog(`发送请求: ${JSON.stringify(request, null, 2)}`);
      const response = await register(request);
      addLog(`✅ 注册成功!`);
      addLog(`响应: ${JSON.stringify(response, null, 2)}`);
    } catch (error: any) {
      addLog(`❌ 注册失败: ${error.message}`);
      if (error.response?.data) {
        addLog(`错误详情: ${JSON.stringify(error.response.data, null, 2)}`);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleLogin = async () => {
    setLoading(true);
    clearLog();
    try {
      addLog('🔐 测试登录...');
      const request: LoginBody = {
        username: 'testuser',
        password: 'password123',
      };
      
      addLog(`发送请求: ${JSON.stringify(request, null, 2)}`);
      const response = await login(request);
      addLog(`✅ 登录成功!`);
      addLog(`响应 (注意 camelCase): ${JSON.stringify(response, null, 2)}`);
      
      // 验证响应字段是否为 camelCase
      if (response.accessToken) {
        addLog(`✅ 验证: accessToken 字段存在 (camelCase) ✓`);
        setToken(response.accessToken);
        setAuthToken(response.accessToken);
      } else {
        addLog(`❌ 错误: accessToken 字段不存在!`);
      }
    } catch (error: any) {
      addLog(`❌ 登录失败: ${error.message}`);
      if (error.response?.data) {
        addLog(`错误详情: ${JSON.stringify(error.response.data, null, 2)}`);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleListClusters = async () => {
    setLoading(true);
    clearLog();
    try {
      addLog('📋 测试获取集群列表...');
      const clusters = await listClusters();
      addLog(`✅ 获取成功! 共 ${clusters.length} 个集群`);
      addLog(`响应 (注意 camelCase): ${JSON.stringify(clusters, null, 2)}`);
      
      // 验证响应字段
      if (clusters.length > 0) {
        const firstCluster = clusters[0];
        if ('createdAt' in firstCluster) {
          addLog(`✅ 验证: createdAt 字段存在 (camelCase) ✓`);
        }
        if ('hasCaData' in firstCluster) {
          addLog(`✅ 验证: hasCaData 字段存在 (camelCase) ✓`);
        }
      }
    } catch (error: any) {
      addLog(`❌ 获取失败: ${error.message}`);
      if (error.response?.data) {
        addLog(`错误详情: ${JSON.stringify(error.response.data, null, 2)}`);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleCreateCluster = async () => {
    setLoading(true);
    clearLog();
    try {
      addLog('🚀 测试创建集群 (使用 camelCase)...');
      const request: CreateClusterRequest = {
        name: 'test-cluster',
        host: 'https://k8s.test.example.com:6443',
        description: '测试集群 - camelCase 验证',
        caData: 'LS0tLS1CRUdJTi1DRVJUSUZJQ0FURS0tLS0t',  // ✅ camelCase
        certData: 'LS0tLS1CRUdJTi1DRVJUSUZJQ0FURS0tLS0t', // ✅ camelCase
        keyData: 'LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVkt',   // ✅ camelCase
      };
      
      addLog(`发送请求 (camelCase):`);
      addLog(JSON.stringify(request, null, 2));
      
      const response = await createCluster(request);
      addLog(`✅ 创建成功!`);
      addLog(`响应: ${JSON.stringify(response, null, 2)}`);
      
      // 验证响应字段
      if ('createdAt' in response) {
        addLog(`✅ 验证: createdAt 字段存在 (camelCase) ✓`);
      }
      if ('caData' in response || 'hasCaData' in response) {
        addLog(`✅ 验证: caData/hasCaData 字段存在 (camelCase) ✓`);
      }
    } catch (error: any) {
      addLog(`❌ 创建失败: ${error.message}`);
      if (error.response?.data) {
        addLog(`错误详情: ${JSON.stringify(error.response.data, null, 2)}`);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleFullTest = async () => {
    setLoading(true);
    clearLog();
    addLog('🧪 开始完整测试流程...\n');
    
    try {
      // 1. 注册
      addLog('步骤 1: 注册用户');
      try {
        await register({
          username: `testuser_${Date.now()}`,
          password: 'password123',
        });
        addLog('✅ 注册成功\n');
      } catch (e: any) {
        addLog('⚠️ 注册失败 (可能用户已存在)\n');
      }

      // 2. 登录
      addLog('步骤 2: 登录');
      const loginResponse = await login({
        username: 'testuser',
        password: 'password123',
      });
      addLog(`✅ 登录成功 - Token: ${loginResponse.accessToken?.substring(0, 20)}...`);
      setAuthToken(loginResponse.accessToken || '');
      addLog('');

      // 3. 获取集群列表
      addLog('步骤 3: 获取集群列表');
      const clusters = await listClusters();
      addLog(`✅ 获取成功 - 共 ${clusters.length} 个集群\n`);

      // 4. 创建集群
      addLog('步骤 4: 创建测试集群 (camelCase)');
      const newCluster = await createCluster({
        name: `test-cluster-${Date.now()}`,
        host: 'https://k8s.test.example.com:6443',
        description: 'Full test cluster',
        caData: 'LS0tLS1CRUdJTi1DRVJUSUZJQ0FURS0tLS0t',
        certData: 'LS0tLS1CRUdJTi1DRVJUSUZJQ0FURS0tLS0t',
        keyData: 'LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVkt',
      });
      addLog(`✅ 创建成功 - ID: ${newCluster.id}\n`);

      addLog('🎉 完整测试流程完成! 所有 API 调用成功，camelCase 工作正常！');
    } catch (error: any) {
      addLog(`\n❌ 测试失败: ${error.message}`);
      if (error.response?.data) {
        addLog(`错误详情: ${JSON.stringify(error.response.data, null, 2)}`);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: '20px', fontFamily: 'monospace' }}>
      <h1>🧪 OCDP API 测试 - camelCase 验证</h1>
      
      <div style={{ marginBottom: '20px' }}>
        <h3>当前 Token:</h3>
        <input
          type="text"
          value={token}
          onChange={(e) => setToken(e.target.value)}
          placeholder="JWT Token"
          style={{ width: '100%', padding: '8px', marginBottom: '10px' }}
        />
        <button onClick={() => setAuthToken(token)}>设置 Token</button>
      </div>

      <div style={{ marginBottom: '20px' }}>
        <h3>测试选项:</h3>
        <button onClick={handleRegister} disabled={loading} style={{ marginRight: '10px' }}>
          1. 测试注册
        </button>
        <button onClick={handleLogin} disabled={loading} style={{ marginRight: '10px' }}>
          2. 测试登录
        </button>
        <button onClick={handleListClusters} disabled={loading} style={{ marginRight: '10px' }}>
          3. 获取集群列表
        </button>
        <button onClick={handleCreateCluster} disabled={loading} style={{ marginRight: '10px' }}>
          4. 创建集群 (camelCase)
        </button>
        <button
          onClick={handleFullTest}
          disabled={loading}
          style={{ marginRight: '10px', fontWeight: 'bold', backgroundColor: '#4CAF50', color: 'white' }}
        >
          🚀 完整测试
        </button>
        <button onClick={clearLog} disabled={loading}>
          清除日志
        </button>
      </div>

      <div
        style={{
          backgroundColor: '#1e1e1e',
          color: '#d4d4d4',
          padding: '15px',
          borderRadius: '5px',
          minHeight: '400px',
          maxHeight: '600px',
          overflow: 'auto',
          whiteSpace: 'pre-wrap',
          fontSize: '12px',
        }}
      >
        {result || '点击按钮开始测试...'}
      </div>

      {loading && (
        <div style={{ marginTop: '10px', color: '#2196F3' }}>
          ⏳ 正在执行测试...
        </div>
      )}
    </div>
  );
}
