import React, { useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { Bug, Play, CheckCircle, AlertCircle } from 'lucide-react';

interface DebugResult {
  command: string;
  success: boolean;
  data?: any;
  error?: string;
  timestamp: string;
}

/**
 * JSON解析器调试面板
 * 用于测试后端命令是否正常工作
 */
const JsonParserDebugPanel: React.FC = () => {
  const [results, setResults] = useState<DebugResult[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  const addResult = (command: string, success: boolean, data?: any, error?: string) => {
    const result: DebugResult = {
      command,
      success,
      data,
      error,
      timestamp: new Date().toLocaleTimeString()
    };
    setResults(prev => [result, ...prev]);
  };

  // 测试基本的JSON解析
  const testBasicParse = async () => {
    setIsLoading(true);
    try {
      const request = {
        text: '{"name": "test", "value": 123}',
        config: {
          enable_unquoted_keys: true,
          enable_trailing_commas: true
        }
      };

      console.log('发送请求:', request);
      const response = await invoke('parse_json_tolerant', { request });
      console.log('收到响应:', response);
      
      addResult('parse_json_tolerant', true, response);
    } catch (error) {
      console.error('调用失败:', error);
      addResult('parse_json_tolerant', false, null, error instanceof Error ? error.message : '未知错误');
    } finally {
      setIsLoading(false);
    }
  };

  // 测试验证JSON
  const testValidateJson = async () => {
    setIsLoading(true);
    try {
      const result = await invoke('validate_json_format', { text: '{"valid": true}' });
      addResult('validate_json_format', true, result);
    } catch (error) {
      addResult('validate_json_format', false, null, error instanceof Error ? error.message : '未知错误');
    } finally {
      setIsLoading(false);
    }
  };

  // 测试获取恢复策略
  const testGetStrategies = async () => {
    setIsLoading(true);
    try {
      const result = await invoke('get_recovery_strategies');
      addResult('get_recovery_strategies', true, result);
    } catch (error) {
      addResult('get_recovery_strategies', false, null, error instanceof Error ? error.message : '未知错误');
    } finally {
      setIsLoading(false);
    }
  };

  // 测试获取默认配置
  const testGetDefaultConfig = async () => {
    setIsLoading(true);
    try {
      const result = await invoke('get_default_parser_config');
      addResult('get_default_parser_config', true, result);
    } catch (error) {
      addResult('get_default_parser_config', false, null, error instanceof Error ? error.message : '未知错误');
    } finally {
      setIsLoading(false);
    }
  };

  // 测试Markdown包裹的JSON
  const testMarkdownJson = async () => {
    setIsLoading(true);
    try {
      const request = {
        text: `这是一个JSON示例：
\`\`\`json
{
  "user": {
    "name": "张三",
    "age": 25,
    "hobbies": ["编程", "音乐"]
  }
}
\`\`\`
请处理这个数据。`,
        config: {
          enable_unquoted_keys: true,
          enable_trailing_commas: true
        }
      };

      console.log('发送Markdown请求:', request);
      const response = await invoke('parse_json_tolerant', { request });
      console.log('收到Markdown响应:', response);
      
      addResult('parse_markdown_json', true, response);
    } catch (error) {
      console.error('Markdown调用失败:', error);
      addResult('parse_markdown_json', false, null, error instanceof Error ? error.message : '未知错误');
    } finally {
      setIsLoading(false);
    }
  };

  const clearResults = () => {
    setResults([]);
  };

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
      <div className="p-6 border-b border-gray-200">
        <div className="flex items-center gap-3">
          <Bug className="w-6 h-6 text-orange-600" />
          <div>
            <h2 className="text-lg font-semibold text-gray-900">JSON解析器调试面板</h2>
            <p className="text-sm text-gray-600">测试后端命令是否正常工作</p>
          </div>
        </div>
      </div>

      <div className="p-6 space-y-6">
        {/* 测试按钮 */}
        <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
          <button
            onClick={testBasicParse}
            disabled={isLoading}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-300 text-white rounded-lg font-medium transition-colors"
          >
            <Play className="w-4 h-4" />
            基本解析
          </button>

          <button
            onClick={testMarkdownJson}
            disabled={isLoading}
            className="flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-300 text-white rounded-lg font-medium transition-colors"
          >
            <Play className="w-4 h-4" />
            Markdown解析
          </button>

          <button
            onClick={testValidateJson}
            disabled={isLoading}
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-300 text-white rounded-lg font-medium transition-colors"
          >
            <Play className="w-4 h-4" />
            验证JSON
          </button>

          <button
            onClick={testGetStrategies}
            disabled={isLoading}
            className="flex items-center gap-2 px-4 py-2 bg-yellow-600 hover:bg-yellow-700 disabled:bg-gray-300 text-white rounded-lg font-medium transition-colors"
          >
            <Play className="w-4 h-4" />
            获取策略
          </button>

          <button
            onClick={testGetDefaultConfig}
            disabled={isLoading}
            className="flex items-center gap-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:bg-gray-300 text-white rounded-lg font-medium transition-colors"
          >
            <Play className="w-4 h-4" />
            默认配置
          </button>

          <button
            onClick={clearResults}
            className="flex items-center gap-2 px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg font-medium transition-colors"
          >
            清空结果
          </button>
        </div>

        {/* 结果显示 */}
        {results.length > 0 && (
          <div className="space-y-3">
            <h3 className="text-sm font-medium text-gray-900">测试结果</h3>
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {results.map((result, index) => (
                <div
                  key={index}
                  className={`p-3 rounded-lg border ${
                    result.success 
                      ? 'bg-green-50 border-green-200' 
                      : 'bg-red-50 border-red-200'
                  }`}
                >
                  <div className="flex items-start gap-3">
                    {result.success ? (
                      <CheckCircle className="w-5 h-5 text-green-600 mt-0.5 flex-shrink-0" />
                    ) : (
                      <AlertCircle className="w-5 h-5 text-red-600 mt-0.5 flex-shrink-0" />
                    )}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <span className={`text-sm font-medium ${
                          result.success ? 'text-green-800' : 'text-red-800'
                        }`}>
                          {result.command}
                        </span>
                        <span className="text-xs text-gray-500">{result.timestamp}</span>
                      </div>
                      
                      {result.error && (
                        <p className="text-sm text-red-700 mb-2">{result.error}</p>
                      )}
                      
                      {result.data && (
                        <pre className="text-xs text-gray-700 bg-white p-2 rounded border overflow-auto max-h-32">
                          {JSON.stringify(result.data, null, 2)}
                        </pre>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default JsonParserDebugPanel;
