/**
 * 执行详情查看器组件
 * 
 * 显示工作流执行的完整详情信息，包括输入输出数据、错误日志等
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState } from 'react';
import { 
  X, 
  Clock, 
  CheckCircle, 
  XCircle, 
  AlertCircle, 
  RefreshCw,
  Download,
  Copy,
  Eye,
  Code,
  Image as ImageIcon,
  FileText,
  Calendar,
  Server,
  User,
  Tag
} from 'lucide-react';

// 执行状态枚举
type ExecutionStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';

// 执行记录接口
interface WorkflowExecutionRecord {
  id: number;
  workflow_template_id: number;
  workflow_name: string;
  workflow_version: string;
  execution_environment_id?: number;
  execution_environment_name?: string;
  input_data_json: any;
  output_data_json?: any;
  status: ExecutionStatus;
  progress: number;
  comfyui_prompt_id?: string;
  comfyui_workflow_name?: string;
  started_at?: string;
  completed_at?: string;
  duration_seconds?: number;
  error_message?: string;
  error_details_json?: any;
  user_id?: string;
  session_id?: string;
  metadata_json?: any;
  tags?: string[];
  created_at: string;
  updated_at: string;
}

interface ExecutionDetailViewerProps {
  /** 执行记录 */
  record: WorkflowExecutionRecord;
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 关闭回调 */
  onClose: () => void;
  /** 下载结果回调 */
  onDownload?: (record: WorkflowExecutionRecord) => void;
  /** 重试回调 */
  onRetry?: (record: WorkflowExecutionRecord) => void;
}

/**
 * 执行详情查看器组件
 */
export const ExecutionDetailViewer: React.FC<ExecutionDetailViewerProps> = ({
  record,
  isOpen,
  onClose,
  onDownload,
  onRetry
}) => {
  const [activeTab, setActiveTab] = useState<'overview' | 'input' | 'output' | 'logs' | 'timeline'>('overview');
  const [showRawData, setShowRawData] = useState(false);

  if (!isOpen) return null;

  // 获取状态图标和颜色
  const getStatusIcon = (status: ExecutionStatus) => {
    switch (status) {
      case 'pending':
        return <Clock className="w-5 h-5 text-yellow-500" />;
      case 'running':
        return <RefreshCw className="w-5 h-5 text-blue-500 animate-spin" />;
      case 'completed':
        return <CheckCircle className="w-5 h-5 text-green-500" />;
      case 'failed':
        return <XCircle className="w-5 h-5 text-red-500" />;
      case 'cancelled':
        return <AlertCircle className="w-5 h-5 text-gray-500" />;
      default:
        return <Clock className="w-5 h-5 text-gray-400" />;
    }
  };

  // 获取状态文本
  const getStatusText = (status: ExecutionStatus) => {
    const statusMap = {
      pending: '等待中',
      running: '执行中',
      completed: '已完成',
      failed: '失败',
      cancelled: '已取消'
    };
    return statusMap[status] || '未知';
  };

  // 格式化时间
  const formatTime = (timeString?: string) => {
    if (!timeString) return '-';
    return new Date(timeString).toLocaleString('zh-CN');
  };

  // 格式化持续时间
  const formatDuration = (seconds?: number) => {
    if (!seconds) return '-';
    
    if (seconds < 60) {
      return `${seconds}秒`;
    } else if (seconds < 3600) {
      return `${Math.floor(seconds / 60)}分${seconds % 60}秒`;
    } else {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      return `${hours}小时${minutes}分钟`;
    }
  };

  // 复制到剪贴板
  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      // TODO: 显示成功提示
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  // 渲染JSON数据
  const renderJsonData = (data: any, title: string) => {
    if (!data) {
      return (
        <div className="text-center py-8 text-gray-500">
          暂无{title}数据
        </div>
      );
    }

    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h4 className="text-sm font-medium text-gray-900">{title}</h4>
          <div className="flex items-center space-x-2">
            <button
              onClick={() => setShowRawData(!showRawData)}
              className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors flex items-center space-x-1"
            >
              <Code className="w-3 h-3" />
              <span>{showRawData ? '格式化' : '原始数据'}</span>
            </button>
            <button
              onClick={() => copyToClipboard(JSON.stringify(data, null, 2))}
              className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors flex items-center space-x-1"
            >
              <Copy className="w-3 h-3" />
              <span>复制</span>
            </button>
          </div>
        </div>
        
        <div className="bg-gray-50 rounded-lg p-4 overflow-auto max-h-96">
          <pre className="text-sm text-gray-800 whitespace-pre-wrap">
            {showRawData ? JSON.stringify(data) : JSON.stringify(data, null, 2)}
          </pre>
        </div>
      </div>
    );
  };

  // 渲染概览标签页
  const renderOverviewTab = () => (
    <div className="space-y-6">
      {/* 基本信息 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="space-y-4">
          <h4 className="text-sm font-medium text-gray-900 flex items-center space-x-2">
            <FileText className="w-4 h-4" />
            <span>基本信息</span>
          </h4>
          <div className="space-y-3">
            <div className="flex justify-between">
              <span className="text-sm text-gray-500">执行ID:</span>
              <span className="text-sm text-gray-900 font-mono">{record.id}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-sm text-gray-500">工作流:</span>
              <span className="text-sm text-gray-900">{record.workflow_name}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-sm text-gray-500">版本:</span>
              <span className="text-sm text-gray-900">v{record.workflow_version}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-sm text-gray-500">状态:</span>
              <div className="flex items-center space-x-2">
                {getStatusIcon(record.status)}
                <span className="text-sm text-gray-900">{getStatusText(record.status)}</span>
              </div>
            </div>
            {record.progress > 0 && record.status === 'running' && (
              <div className="flex justify-between">
                <span className="text-sm text-gray-500">进度:</span>
                <span className="text-sm text-gray-900">{record.progress}%</span>
              </div>
            )}
          </div>
        </div>

        <div className="space-y-4">
          <h4 className="text-sm font-medium text-gray-900 flex items-center space-x-2">
            <Calendar className="w-4 h-4" />
            <span>时间信息</span>
          </h4>
          <div className="space-y-3">
            <div className="flex justify-between">
              <span className="text-sm text-gray-500">创建时间:</span>
              <span className="text-sm text-gray-900">{formatTime(record.created_at)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-sm text-gray-500">开始时间:</span>
              <span className="text-sm text-gray-900">{formatTime(record.started_at)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-sm text-gray-500">完成时间:</span>
              <span className="text-sm text-gray-900">{formatTime(record.completed_at)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-sm text-gray-500">执行耗时:</span>
              <span className="text-sm text-gray-900">{formatDuration(record.duration_seconds)}</span>
            </div>
          </div>
        </div>
      </div>

      {/* 执行环境信息 */}
      {record.execution_environment_name && (
        <div className="space-y-4">
          <h4 className="text-sm font-medium text-gray-900 flex items-center space-x-2">
            <Server className="w-4 h-4" />
            <span>执行环境</span>
          </h4>
          <div className="bg-gray-50 rounded-lg p-4">
            <div className="flex justify-between">
              <span className="text-sm text-gray-500">环境名称:</span>
              <span className="text-sm text-gray-900">{record.execution_environment_name}</span>
            </div>
            {record.comfyui_prompt_id && (
              <div className="flex justify-between mt-2">
                <span className="text-sm text-gray-500">ComfyUI任务ID:</span>
                <span className="text-sm text-gray-900 font-mono">{record.comfyui_prompt_id}</span>
              </div>
            )}
          </div>
        </div>
      )}

      {/* 错误信息 */}
      {record.error_message && (
        <div className="space-y-4">
          <h4 className="text-sm font-medium text-gray-900 flex items-center space-x-2">
            <XCircle className="w-4 h-4 text-red-500" />
            <span>错误信息</span>
          </h4>
          <div className="bg-red-50 border border-red-200 rounded-lg p-4">
            <p className="text-sm text-red-700">{record.error_message}</p>
            {record.error_details_json && (
              <details className="mt-2">
                <summary className="text-sm text-red-600 cursor-pointer hover:text-red-800">
                  查看详细错误信息
                </summary>
                <pre className="mt-2 text-xs text-red-600 bg-red-100 p-2 rounded overflow-auto">
                  {JSON.stringify(record.error_details_json, null, 2)}
                </pre>
              </details>
            )}
          </div>
        </div>
      )}

      {/* 标签 */}
      {record.tags && record.tags.length > 0 && (
        <div className="space-y-4">
          <h4 className="text-sm font-medium text-gray-900 flex items-center space-x-2">
            <Tag className="w-4 h-4" />
            <span>标签</span>
          </h4>
          <div className="flex flex-wrap gap-2">
            {record.tags.map((tag, index) => (
              <span
                key={index}
                className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full"
              >
                {tag}
              </span>
            ))}
          </div>
        </div>
      )}
    </div>
  );

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] flex flex-col">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center space-x-3">
            {getStatusIcon(record.status)}
            <div>
              <h2 className="text-lg font-semibold text-gray-900">
                执行详情 - {record.workflow_name}
              </h2>
              <p className="text-sm text-gray-500">
                ID: {record.id} | v{record.workflow_version}
              </p>
            </div>
          </div>
          
          <div className="flex items-center space-x-2">
            {record.status === 'failed' && onRetry && (
              <button
                onClick={() => onRetry(record)}
                className="px-3 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors flex items-center space-x-1"
              >
                <RefreshCw className="w-4 h-4" />
                <span>重试</span>
              </button>
            )}

            {record.status === 'failed' && (
              <button
                onClick={() => {
                  // TODO: 打开错误分析器
                  console.log('分析错误:', record);
                }}
                className="px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 transition-colors flex items-center space-x-1"
              >
                <AlertCircle className="w-4 h-4" />
                <span>错误分析</span>
              </button>
            )}
            
            {record.output_data_json && onDownload && (
              <button
                onClick={() => onDownload(record)}
                className="px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors flex items-center space-x-1"
              >
                <Download className="w-4 h-4" />
                <span>下载</span>
              </button>
            )}
            
            <button
              onClick={onClose}
              className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* 标签导航 */}
        <div className="border-b border-gray-200">
          <nav className="flex space-x-8 px-6">
            {[
              { id: 'overview', label: '概览', icon: Eye },
              { id: 'input', label: '输入数据', icon: FileText },
              { id: 'output', label: '输出结果', icon: ImageIcon },
              { id: 'logs', label: '执行日志', icon: Code },
              { id: 'timeline', label: '时间线', icon: Clock }
            ].map(({ id, label, icon: Icon }) => (
              <button
                key={id}
                onClick={() => setActiveTab(id as any)}
                className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors flex items-center space-x-2 ${
                  activeTab === id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                <Icon className="w-4 h-4" />
                <span>{label}</span>
              </button>
            ))}
          </nav>
        </div>

        {/* 内容区域 */}
        <div className="flex-1 overflow-y-auto p-6">
          {activeTab === 'overview' && renderOverviewTab()}
          {activeTab === 'input' && renderJsonData(record.input_data_json, '输入数据')}
          {activeTab === 'output' && renderJsonData(record.output_data_json, '输出结果')}
          {activeTab === 'logs' && renderJsonData(record.error_details_json, '执行日志')}
          {activeTab === 'timeline' && (
            <div className="text-center py-8 text-gray-500">
              时间线功能开发中...
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
