import React, { useState, useCallback } from 'react';
import { 
  Code, 
  CheckCircle, 
  AlertCircle, 
  Copy, 
  Download, 
  Loader2,
  RefreshCw,
  Settings,
  Info
} from 'lucide-react';
import { save } from '@tauri-apps/plugin-dialog';
import { useNotifications } from './NotificationSystem';
import TolerantJsonService, {
  JsonParserConfig,
  ParseStatistics,
  ParseJsonRequest
} from '../services/tolerantJsonService';

/**
 * 容错JSON解析器组件
 * 支持处理大模型返回的不规范JSON数据
 */
const TolerantJsonParser: React.FC = () => {
  const [inputText, setInputText] = useState('');
  const [outputData, setOutputData] = useState<any>(null);
  const [statistics, setStatistics] = useState<ParseStatistics | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [showConfig, setShowConfig] = useState(false);
  const [config, setConfig] = useState<JsonParserConfig>({
    max_text_length: 1024 * 1024,
    enable_comments: true,
    enable_unquoted_keys: true,
    enable_trailing_commas: true,
    timeout_ms: 30000,
    recovery_strategies: ['StandardJson', 'ManualFix', 'RegexExtract', 'PartialParse']
  });

  const { success, error: notifyError } = useNotifications();

  // 解析JSON
  const parseJson = useCallback(async () => {
    if (!inputText.trim()) {
      notifyError('输入错误', '请输入要解析的JSON文本');
      return;
    }

    setIsLoading(true);
    setError(null);
    setOutputData(null);
    setStatistics(null);

    try {
      const request: ParseJsonRequest = {
        text: inputText,
        config: config
      };

      const response = await TolerantJsonService.parseJson(request);

      if (response.success) {
        setOutputData(response.data);
        setStatistics(response.statistics || null);
        success('解析成功', `解析完成，用时 ${response.statistics?.parse_time_ms || 0}ms`);
      } else {
        setError(response.error || '解析失败');
        notifyError('解析失败', response.error || '未知错误');
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '解析失败';
      setError(errorMessage);
      notifyError('解析失败', errorMessage);
    } finally {
      setIsLoading(false);
    }
  }, [inputText, config, success, notifyError]);

  // 格式化JSON
  const formatJson = useCallback(async () => {
    if (!inputText.trim()) {
      notifyError('输入错误', '请输入要格式化的JSON文本');
      return;
    }

    try {
      const formatted = await TolerantJsonService.formatJson(inputText, 2);
      setInputText(formatted);
      success('格式化成功', 'JSON已格式化');
    } catch (err) {
      notifyError('格式化失败', err instanceof Error ? err.message : '格式化失败');
    }
  }, [inputText, success, notifyError]);

  // 验证JSON
  const validateJson = useCallback(async () => {
    if (!inputText.trim()) {
      notifyError('输入错误', '请输入要验证的JSON文本');
      return;
    }

    try {
      const isValid = await TolerantJsonService.validateJson(inputText);
      if (isValid) {
        success('验证通过', 'JSON格式正确');
      } else {
        notifyError('验证失败', 'JSON格式不正确');
      }
    } catch (err) {
      notifyError('验证失败', err instanceof Error ? err.message : '验证失败');
    }
  }, [inputText, success, notifyError]);

  // 复制结果
  const copyResult = useCallback(async () => {
    if (!outputData) return;

    try {
      const jsonString = JSON.stringify(outputData, null, 2);
      await navigator.clipboard.writeText(jsonString);
      success('复制成功', '解析结果已复制到剪贴板');
    } catch (err) {
      notifyError('复制失败', '无法复制到剪贴板');
    }
  }, [outputData, success, notifyError]);

  // 导出结果
  const exportResult = useCallback(async () => {
    if (!outputData) return;

    try {
      const filePath = await save({
        filters: [{
          name: 'JSON Files',
          extensions: ['json']
        }],
        defaultPath: 'parsed_result.json'
      });

      if (filePath) {
        // 这里需要调用后端保存文件的命令
        // const jsonString = JSON.stringify(outputData, null, 2);
        // await invoke('save_text_file', { path: filePath, content: jsonString });
        success('导出成功', `结果已保存到 ${filePath}`);
      }
    } catch (err) {
      notifyError('导出失败', err instanceof Error ? err.message : '导出失败');
    }
  }, [outputData, success, notifyError]);

  // 清空内容
  const clearAll = useCallback(() => {
    setInputText('');
    setOutputData(null);
    setStatistics(null);
    setError(null);
  }, []);

  // 示例数据
  const loadExample = useCallback((example: string) => {
    const examples = {
      'markdown': `这是一个JSON示例：
\`\`\`json
{
  "user": {
    "name": "张三",
    "age": 25,
    "hobbies": ["编程", "音乐"]
  }
}
\`\`\`
请处理这个数据。`,
      'malformed': `{
  name: "李四",
  age: 30,
  skills: ["JavaScript", "Python",],
  active: true,
}`,
      'mixed': `AI模型返回：
{
  "analysis": {
    sentiment: "positive",
    confidence: 0.85,
    keywords: ['good', 'excellent']
  }
}`
    };
    setInputText(examples[example as keyof typeof examples] || '');
  }, []);

  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 justify-between">
          <div className="flex items-center gap-3">
            <Code className="w-6 h-6 text-blue-600" />
            <div>
              <h2 className="text-lg font-semibold text-gray-900">容错JSON解析器</h2>
              <p className="text-sm text-gray-600">处理大模型返回的不规范JSON数据</p>
            </div>
          </div>
          <button
            onClick={() => setShowConfig(!showConfig)}
            className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <Settings className="w-4 h-4" />
            配置
          </button>
        </div>
      </div>

      <div className="p-6 space-y-6">
        {/* 配置面板 */}
        {showConfig && (
          <div className="bg-gray-50 rounded-lg p-4 space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-medium text-gray-900">解析配置</h3>
              <div className="flex gap-2">
                <button
                  onClick={() => setConfig(TolerantJsonService.getPresetConfigs().strict)}
                  className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded hover:bg-red-200 transition-colors"
                >
                  严格
                </button>
                <button
                  onClick={() => setConfig(TolerantJsonService.getPresetConfigs().lenient)}
                  className="px-2 py-1 text-xs bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors"
                >
                  宽松
                </button>
                <button
                  onClick={() => setConfig(TolerantJsonService.getPresetConfigs().ai_model)}
                  className="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors"
                >
                  AI模式
                </button>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.enable_comments}
                  onChange={(e) => setConfig(prev => ({ ...prev, enable_comments: e.target.checked }))}
                  className="rounded border-gray-300"
                />
                <span className="text-sm text-gray-700">支持注释</span>
              </label>
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.enable_unquoted_keys}
                  onChange={(e) => setConfig(prev => ({ ...prev, enable_unquoted_keys: e.target.checked }))}
                  className="rounded border-gray-300"
                />
                <span className="text-sm text-gray-700">无引号键</span>
              </label>
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.enable_trailing_commas}
                  onChange={(e) => setConfig(prev => ({ ...prev, enable_trailing_commas: e.target.checked }))}
                  className="rounded border-gray-300"
                />
                <span className="text-sm text-gray-700">尾随逗号</span>
              </label>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs text-gray-600 mb-1">超时时间 (ms)</label>
                <input
                  type="number"
                  value={config.timeout_ms || 30000}
                  onChange={(e) => setConfig(prev => ({ ...prev, timeout_ms: parseInt(e.target.value) }))}
                  className="w-full px-2 py-1 text-sm border border-gray-300 rounded"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-600 mb-1">最大长度 (bytes)</label>
                <input
                  type="number"
                  value={config.max_text_length || 1024 * 1024}
                  onChange={(e) => setConfig(prev => ({ ...prev, max_text_length: parseInt(e.target.value) }))}
                  className="w-full px-2 py-1 text-sm border border-gray-300 rounded"
                />
              </div>
            </div>
          </div>
        )}

        {/* 示例按钮 */}
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm text-gray-600">示例：</span>
          <button
            onClick={() => loadExample('markdown')}
            className="px-3 py-1 text-xs bg-blue-100 text-blue-700 rounded-full hover:bg-blue-200 transition-colors"
          >
            Markdown包裹
          </button>
          <button
            onClick={() => loadExample('malformed')}
            className="px-3 py-1 text-xs bg-orange-100 text-orange-700 rounded-full hover:bg-orange-200 transition-colors"
          >
            格式错误
          </button>
          <button
            onClick={() => loadExample('mixed')}
            className="px-3 py-1 text-xs bg-green-100 text-green-700 rounded-full hover:bg-green-200 transition-colors"
          >
            混合内容
          </button>
        </div>

        {/* 输入区域 */}
        <div className="space-y-2">
          <label className="block text-sm font-medium text-gray-700">
            输入JSON文本
          </label>
          <textarea
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            placeholder="输入或粘贴JSON文本..."
            className="w-full h-40 p-3 border border-gray-300 rounded-lg resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono text-sm"
          />
        </div>

        {/* 操作按钮 */}
        <div className="flex gap-2 flex-wrap">
          <button
            onClick={parseJson}
            disabled={isLoading || !inputText.trim()}
            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"
          >
            {isLoading ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Code className="w-4 h-4" />
            )}
            {isLoading ? '解析中...' : '解析JSON'}
          </button>

          <button
            onClick={formatJson}
            disabled={!inputText.trim()}
            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"
          >
            <RefreshCw className="w-4 h-4" />
            格式化
          </button>

          <button
            onClick={validateJson}
            disabled={!inputText.trim()}
            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"
          >
            <CheckCircle className="w-4 h-4" />
            验证
          </button>

          <button
            onClick={clearAll}
            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"
          >
            <RefreshCw className="w-4 h-4" />
            清空
          </button>
        </div>

        {/* 错误显示 */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4">
            <div className="flex items-start gap-3">
              <AlertCircle className="w-5 h-5 text-red-600 mt-0.5 flex-shrink-0" />
              <div>
                <p className="font-medium text-red-800">解析失败</p>
                <p className="text-sm text-red-700 mt-1">{error}</p>
              </div>
            </div>
          </div>
        )}

        {/* 统计信息 */}
        {statistics && (
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div className="flex items-start gap-3">
              <Info className="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" />
              <div className="flex-1">
                <p className="font-medium text-blue-800 mb-2">解析统计</p>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div>
                    <span className="text-blue-600">解析时间:</span>
                    <span className="ml-1 font-medium">{statistics.parse_time_ms}ms</span>
                  </div>
                  <div>
                    <span className="text-blue-600">错误率:</span>
                    <span className="ml-1 font-medium">{(statistics.error_rate * 100).toFixed(1)}%</span>
                  </div>
                  <div>
                    <span className="text-blue-600">总节点:</span>
                    <span className="ml-1 font-medium">{statistics.total_nodes}</span>
                  </div>
                  <div>
                    <span className="text-blue-600">错误节点:</span>
                    <span className="ml-1 font-medium">{statistics.error_nodes}</span>
                  </div>
                </div>
                {statistics.recovery_strategies_used.length > 0 && (
                  <div className="mt-3">
                    <span className="text-blue-600 text-sm">使用的恢复策略:</span>
                    <div className="flex gap-1 mt-1 flex-wrap">
                      {statistics.recovery_strategies_used.map((strategy, index) => (
                        <span
                          key={index}
                          className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full"
                        >
                          {strategy}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}

        {/* 解析结果 */}
        {outputData && (
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-medium text-gray-900">解析结果</h3>
              <div className="flex gap-2">
                <button
                  onClick={copyResult}
                  className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <Copy className="w-4 h-4" />
                  复制
                </button>
                <button
                  onClick={exportResult}
                  className="flex items-center gap-1 px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <Download className="w-4 h-4" />
                  导出
                </button>
              </div>
            </div>

            <div className="bg-gray-50 rounded-lg p-4">
              <pre className="text-sm text-gray-800 overflow-auto max-h-96 whitespace-pre-wrap font-mono">
                {JSON.stringify(outputData, null, 2)}
              </pre>
            </div>

            {/* 成功提示 */}
            <div className="bg-green-50 border border-green-200 rounded-lg p-4">
              <div className="flex items-start gap-3">
                <CheckCircle className="w-5 h-5 text-green-600 mt-0.5 flex-shrink-0" />
                <div>
                  <p className="font-medium text-green-800">解析成功</p>
                  <p className="text-sm text-green-700 mt-1">
                    JSON数据已成功解析并格式化
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default TolerantJsonParser;
