/**
 * 执行历史列表组件
 * 
 * 显示工作流执行历史记录，支持分页、筛选、搜索和批量操作
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect, useCallback } from 'react';
import { 
  Clock, 
  CheckCircle, 
  XCircle, 
  AlertCircle, 
  Play, 
  Download, 
  Trash2, 
  RefreshCw,
  Search,
  Filter,
  Calendar,
  MoreHorizontal,
  Eye
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';

// 执行状态枚举
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 ExecutionHistoryResponse {
  records: WorkflowExecutionRecord[];
  total_count: number;
  page: number;
  page_size: number;
  total_pages: number;
}

// 筛选器接口
interface ExecutionRecordFilter {
  workflow_template_id?: number;
  status?: ExecutionStatus;
  user_id?: string;
  session_id?: string;
  comfyui_prompt_id?: string;
  date_from?: string;
  date_to?: string;
}

// 组件属性接口
interface ExecutionHistoryListProps {
  /** 筛选条件 */
  filter?: ExecutionRecordFilter;
  /** 查看详情回调 */
  onViewDetails: (record: WorkflowExecutionRecord) => void;
  /** 重试回调 */
  onRetry: (record: WorkflowExecutionRecord) => void;
  /** 删除回调 */
  onDelete: (recordId: number) => void;
  /** 批量删除回调 */
  onBatchDelete?: (recordIds: number[]) => void;
  /** 下载结果回调 */
  onDownload?: (record: WorkflowExecutionRecord) => void;
}

/**
 * 执行历史列表组件
 */
export const ExecutionHistoryList: React.FC<ExecutionHistoryListProps> = ({
  filter,
  onViewDetails,
  onRetry,
  onDelete,
  onBatchDelete,
  onDownload
}) => {
  const [records, setRecords] = useState<WorkflowExecutionRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<ExecutionStatus | ''>('');
  const [dateFilter, setDateFilter] = useState<'today' | 'week' | 'month' | 'all'>('all');
  const [selectedRecords, setSelectedRecords] = useState<Set<number>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [pageSize] = useState(20);

  // 加载执行历史
  const loadExecutionHistory = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      // 构建筛选条件
      const filterConditions: ExecutionRecordFilter = {
        ...filter,
        status: statusFilter || undefined,
      };

      // 添加日期筛选
      if (dateFilter !== 'all') {
        const now = new Date();
        let dateFrom: Date;
        
        switch (dateFilter) {
          case 'today':
            dateFrom = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            break;
          case 'week':
            dateFrom = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
            break;
          case 'month':
            dateFrom = new Date(now.getFullYear(), now.getMonth(), 1);
            break;
          default:
            dateFrom = new Date(0);
        }
        
        filterConditions.date_from = dateFrom.toISOString();
      }

      const result = await invoke<ExecutionHistoryResponse>('get_execution_history', {
        filter: filterConditions,
        limit: pageSize,
        offset: (currentPage - 1) * pageSize
      });

      setRecords(result.records);
      setTotalPages(result.total_pages);
      
    } catch (err) {
      console.error('加载执行历史失败:', err);
      setError('加载执行历史失败');
    } finally {
      setLoading(false);
    }
  }, [filter, statusFilter, dateFilter, currentPage, pageSize]);

  // 初始加载和依赖更新时重新加载
  useEffect(() => {
    loadExecutionHistory();
  }, [loadExecutionHistory]);

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

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

  // 格式化持续时间
  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 formatTime = (timeString?: string) => {
    if (!timeString) return '-';
    return new Date(timeString).toLocaleString('zh-CN');
  };

  // 处理全选/取消全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedRecords(new Set(records.map(r => r.id)));
    } else {
      setSelectedRecords(new Set());
    }
  };

  // 处理单个选择
  const handleSelectRecord = (recordId: number, checked: boolean) => {
    const newSelected = new Set(selectedRecords);
    if (checked) {
      newSelected.add(recordId);
    } else {
      newSelected.delete(recordId);
    }
    setSelectedRecords(newSelected);
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRecords.size > 0 && onBatchDelete) {
      onBatchDelete(Array.from(selectedRecords));
      setSelectedRecords(new Set());
    }
  };

  // 筛选记录
  const filteredRecords = records.filter(record => {
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      return (
        record.workflow_name.toLowerCase().includes(searchLower) ||
        record.comfyui_prompt_id?.toLowerCase().includes(searchLower) ||
        record.error_message?.toLowerCase().includes(searchLower)
      );
    }
    return true;
  });

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <RefreshCw className="w-8 h-8 text-blue-500 animate-spin" />
        <span className="ml-2 text-gray-600">加载执行历史...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex items-center">
          <XCircle className="w-5 h-5 text-red-500 mr-2" />
          <span className="text-red-700">{error}</span>
        </div>
        <button
          onClick={loadExecutionHistory}
          className="mt-2 px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 transition-colors"
        >
          重试
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 搜索和筛选栏 */}
      <div className="flex flex-col sm:flex-row gap-4">
        {/* 搜索框 */}
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            placeholder="搜索工作流名称、任务ID或错误信息..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>

        {/* 状态筛选 */}
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value as ExecutionStatus | '')}
          className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        >
          <option value="">所有状态</option>
          <option value="pending">等待中</option>
          <option value="running">执行中</option>
          <option value="completed">已完成</option>
          <option value="failed">失败</option>
          <option value="cancelled">已取消</option>
        </select>

        {/* 日期筛选 */}
        <select
          value={dateFilter}
          onChange={(e) => setDateFilter(e.target.value as 'today' | 'week' | 'month' | 'all')}
          className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        >
          <option value="all">所有时间</option>
          <option value="today">今天</option>
          <option value="week">最近一周</option>
          <option value="month">最近一月</option>
        </select>

        {/* 刷新按钮 */}
        <button
          onClick={loadExecutionHistory}
          className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center space-x-2"
        >
          <RefreshCw className="w-4 h-4" />
          <span>刷新</span>
        </button>
      </div>

      {/* 批量操作栏 */}
      {selectedRecords.size > 0 && (
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div className="flex items-center justify-between">
            <span className="text-blue-700">
              已选择 {selectedRecords.size} 条记录
            </span>
            <div className="flex items-center space-x-2">
              {onBatchDelete && (
                <button
                  onClick={handleBatchDelete}
                  className="px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 transition-colors flex items-center space-x-1"
                >
                  <Trash2 className="w-4 h-4" />
                  <span>批量删除</span>
                </button>
              )}
              <button
                onClick={() => setSelectedRecords(new Set())}
                className="px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
              >
                取消选择
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 执行记录表格 */}
      {filteredRecords.length === 0 ? (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
          <Clock className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            暂无执行记录
          </h3>
          <p className="text-gray-600">
            {searchTerm || statusFilter || dateFilter !== 'all'
              ? '没有找到匹配的执行记录'
              : '还没有执行过任何工作流'}
          </p>
        </div>
      ) : (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left">
                    <input
                      type="checkbox"
                      checked={selectedRecords.size === filteredRecords.length && filteredRecords.length > 0}
                      onChange={(e) => handleSelectAll(e.target.checked)}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    工作流
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    状态
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    执行环境
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    开始时间
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    耗时
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {filteredRecords.map((record) => (
                  <tr key={record.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4">
                      <input
                        type="checkbox"
                        checked={selectedRecords.has(record.id)}
                        onChange={(e) => handleSelectRecord(record.id, e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex flex-col">
                        <div className="text-sm font-medium text-gray-900">
                          {record.workflow_name}
                        </div>
                        <div className="text-sm text-gray-500">
                          v{record.workflow_version}
                        </div>
                        {record.comfyui_prompt_id && (
                          <div className="text-xs text-gray-400 font-mono">
                            ID: {record.comfyui_prompt_id}
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center space-x-2">
                        {getStatusIcon(record.status)}
                        <span className="text-sm text-gray-900">
                          {getStatusText(record.status)}
                        </span>
                      </div>
                      {record.status === 'running' && (
                        <div className="mt-1">
                          <div className="w-full bg-gray-200 rounded-full h-1.5">
                            <div
                              className="bg-blue-600 h-1.5 rounded-full transition-all duration-300"
                              style={{ width: `${record.progress}%` }}
                            />
                          </div>
                          <div className="text-xs text-gray-500 mt-1">
                            {record.progress}%
                          </div>
                        </div>
                      )}
                      {record.error_message && (
                        <div className="mt-1 text-xs text-red-600 truncate max-w-xs" title={record.error_message}>
                          {record.error_message}
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900">
                        {record.execution_environment_name || '-'}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900">
                        {formatTime(record.started_at)}
                      </div>
                      <div className="text-xs text-gray-500">
                        创建: {formatTime(record.created_at)}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900">
                        {formatDuration(record.duration_seconds)}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center space-x-2">
                        <button
                          onClick={() => onViewDetails(record)}
                          className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                          title="查看详情"
                        >
                          <Eye className="w-4 h-4" />
                        </button>

                        {record.status === 'failed' && (
                          <button
                            onClick={() => onRetry(record)}
                            className="p-1 text-gray-400 hover:text-green-600 transition-colors"
                            title="重试"
                          >
                            <RefreshCw className="w-4 h-4" />
                          </button>
                        )}

                        {record.output_data_json && onDownload && (
                          <button
                            onClick={() => onDownload(record)}
                            className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                            title="下载结果"
                          >
                            <Download className="w-4 h-4" />
                          </button>
                        )}

                        <button
                          onClick={() => onDelete(record.id)}
                          className="p-1 text-gray-400 hover:text-red-600 transition-colors"
                          title="删除"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 分页 */}
          {totalPages > 1 && (
            <div className="bg-white px-4 py-3 border-t border-gray-200 sm:px-6">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <p className="text-sm text-gray-700">
                    显示第 {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, filteredRecords.length)} 条，
                    共 {filteredRecords.length} 条记录
                  </p>
                </div>
                <div className="flex items-center space-x-2">
                  <button
                    onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                    disabled={currentPage === 1}
                    className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    上一页
                  </button>

                  <div className="flex items-center space-x-1">
                    {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                      const page = i + 1;
                      return (
                        <button
                          key={page}
                          onClick={() => setCurrentPage(page)}
                          className={`px-3 py-1 text-sm border rounded ${
                            currentPage === page
                              ? 'bg-blue-600 text-white border-blue-600'
                              : 'border-gray-300 hover:bg-gray-50'
                          }`}
                        >
                          {page}
                        </button>
                      );
                    })}
                  </div>

                  <button
                    onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                    disabled={currentPage === totalPages}
                    className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    下一页
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};
