/**
 * 数据导出管理器组件
 * 
 * 提供多种格式的数据导出功能，支持自定义导出配置
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect } from 'react';
import { 
  Download, 
  FileText, 
  Database, 
  Image, 
  Archive,
  Settings,
  Calendar,
  Filter,
  CheckCircle,
  XCircle,
  RefreshCw,
  AlertCircle,
  Info,
  Eye,
  Clock,
  BarChart3
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import type { 
  WorkflowTemplate, 
  WorkflowExecutionRecord 
} from '../../types/workflow';

// 导出格式枚举
type ExportFormat = 'json' | 'csv' | 'excel' | 'pdf' | 'zip';

// 导出类型枚举
type ExportType = 'templates' | 'executions' | 'results' | 'logs' | 'analytics';

// 导出状态枚举
type ExportStatus = 'pending' | 'preparing' | 'exporting' | 'completed' | 'failed';

// 导出配置接口
interface ExportConfig {
  format: ExportFormat;
  type: ExportType;
  include_metadata: boolean;
  include_results: boolean;
  include_logs: boolean;
  date_range?: {
    start: string;
    end: string;
  };
  filters?: {
    status?: string[];
    workflow_types?: string[];
    environments?: string[];
  };
  compression?: boolean;
  password_protection?: boolean;
  password?: string;
}

// 导出任务接口
interface ExportTask {
  id: string;
  config: ExportConfig;
  status: ExportStatus;
  progress: number;
  total_items: number;
  processed_items: number;
  file_size?: number;
  download_url?: string;
  started_at: string;
  completed_at?: string;
  error_message?: string;
}

// 组件属性接口
interface DataExportManagerProps {
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 关闭回调 */
  onClose: () => void;
  /** 预选的工作流模板 */
  selectedTemplates?: WorkflowTemplate[];
  /** 预选的执行记录 */
  selectedExecutions?: WorkflowExecutionRecord[];
}

/**
 * 数据导出管理器组件
 */
export const DataExportManager: React.FC<DataExportManagerProps> = ({
  isOpen,
  onClose,
  selectedTemplates = [],
  selectedExecutions = []
}) => {
  const [exportConfig, setExportConfig] = useState<ExportConfig>({
    format: 'json',
    type: 'templates',
    include_metadata: true,
    include_results: true,
    include_logs: false,
    compression: false,
    password_protection: false
  });

  const [activeTasks, setActiveTasks] = useState<ExportTask[]>([]);
  const [showAdvancedOptions, setShowAdvancedOptions] = useState(false);

  // 导出格式配置
  const formatConfigs = {
    json: {
      label: 'JSON',
      description: '结构化数据格式，适合程序处理',
      icon: FileText,
      supports: ['templates', 'executions', 'results', 'logs', 'analytics']
    },
    csv: {
      label: 'CSV',
      description: '表格数据格式，适合Excel打开',
      icon: Database,
      supports: ['executions', 'analytics']
    },
    excel: {
      label: 'Excel',
      description: 'Excel工作簿格式，支持多个工作表',
      icon: BarChart3,
      supports: ['templates', 'executions', 'analytics']
    },
    pdf: {
      label: 'PDF',
      description: '便携式文档格式，适合报告',
      icon: FileText,
      supports: ['analytics']
    },
    zip: {
      label: 'ZIP压缩包',
      description: '包含所有相关文件的压缩包',
      icon: Archive,
      supports: ['templates', 'executions', 'results']
    }
  };

  // 导出类型配置
  const typeConfigs = {
    templates: {
      label: '工作流模板',
      description: '导出工作流模板配置和元数据',
      icon: Settings
    },
    executions: {
      label: '执行记录',
      description: '导出工作流执行历史记录',
      icon: Clock
    },
    results: {
      label: '执行结果',
      description: '导出工作流执行的输出结果',
      icon: Image
    },
    logs: {
      label: '执行日志',
      description: '导出详细的执行日志信息',
      icon: FileText
    },
    analytics: {
      label: '分析报告',
      description: '导出统计分析和性能报告',
      icon: BarChart3
    }
  };

  // 获取支持的导出类型
  const getSupportedTypes = (format: ExportFormat): ExportType[] => {
    return formatConfigs[format].supports as ExportType[];
  };

  // 更新导出配置
  const updateConfig = (updates: Partial<ExportConfig>) => {
    setExportConfig(prev => ({ ...prev, ...updates }));
  };

  // 开始导出
  const startExport = async () => {
    const taskId = `export_${Date.now()}`;
    const newTask: ExportTask = {
      id: taskId,
      config: exportConfig,
      status: 'pending',
      progress: 0,
      total_items: getEstimatedItemCount(),
      processed_items: 0,
      started_at: new Date().toISOString()
    };

    setActiveTasks(prev => [...prev, newTask]);

    try {
      // 更新状态为准备中
      updateTaskStatus(taskId, 'preparing');

      // 模拟导出过程
      await simulateExport(taskId);

      // 完成导出
      updateTaskStatus(taskId, 'completed');

    } catch (error) {
      console.error('导出失败:', error);
      updateTaskStatus(taskId, 'failed', error as Error);
    }
  };

  // 模拟导出过程
  const simulateExport = async (taskId: string) => {
    const task = activeTasks.find(t => t.id === taskId);
    if (!task) return;

    updateTaskStatus(taskId, 'exporting');

    // 模拟处理进度
    for (let i = 0; i <= task.total_items; i++) {
      await new Promise(resolve => setTimeout(resolve, 100));
      updateTaskProgress(taskId, i);
    }

    // 生成下载链接
    const downloadUrl = generateDownloadUrl(task.config);
    updateTaskDownloadUrl(taskId, downloadUrl, Math.random() * 10000000); // 随机文件大小
  };

  // 生成下载链接
  const generateDownloadUrl = (config: ExportConfig): string => {
    // 在实际应用中，这里会调用后端API生成真实的下载链接
    const filename = `export_${config.type}_${new Date().toISOString().split('T')[0]}.${config.format}`;
    return `#download/${filename}`;
  };

  // 更新任务状态
  const updateTaskStatus = (taskId: string, status: ExportStatus, error?: Error) => {
    setActiveTasks(prev => prev.map(task => 
      task.id === taskId 
        ? { 
            ...task, 
            status,
            completed_at: status === 'completed' || status === 'failed' ? new Date().toISOString() : undefined,
            error_message: error?.message
          }
        : task
    ));
  };

  // 更新任务进度
  const updateTaskProgress = (taskId: string, processed: number) => {
    setActiveTasks(prev => prev.map(task => 
      task.id === taskId 
        ? { 
            ...task, 
            processed_items: processed,
            progress: Math.round((processed / task.total_items) * 100)
          }
        : task
    ));
  };

  // 更新下载链接
  const updateTaskDownloadUrl = (taskId: string, downloadUrl: string, fileSize: number) => {
    setActiveTasks(prev => prev.map(task => 
      task.id === taskId 
        ? { 
            ...task, 
            download_url: downloadUrl,
            file_size: fileSize
          }
        : task
    ));
  };

  // 估算项目数量
  const getEstimatedItemCount = (): number => {
    switch (exportConfig.type) {
      case 'templates':
        return selectedTemplates.length || 50; // 默认估算
      case 'executions':
        return selectedExecutions.length || 100;
      case 'results':
        return selectedExecutions.length || 100;
      case 'logs':
        return selectedExecutions.length * 10 || 500;
      case 'analytics':
        return 20; // 分析报告项目较少
      default:
        return 10;
    }
  };

  // 获取状态图标
  const getStatusIcon = (status: ExportStatus) => {
    switch (status) {
      case 'pending':
        return <Clock className="w-4 h-4 text-yellow-500" />;
      case 'preparing':
        return <Settings className="w-4 h-4 text-blue-500 animate-spin" />;
      case 'exporting':
        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" />;
      default:
        return <Clock className="w-4 h-4 text-gray-400" />;
    }
  };

  // 格式化文件大小
  const formatFileSize = (bytes?: number): string => {
    if (!bytes) return '-';
    
    const units = ['B', 'KB', 'MB', 'GB'];
    let size = bytes;
    let unitIndex = 0;
    
    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }
    
    return `${size.toFixed(1)} ${units[unitIndex]}`;
  };

  if (!isOpen) return null;

  const currentFormatConfig = formatConfigs[exportConfig.format];
  const currentTypeConfig = typeConfigs[exportConfig.type];
  const supportedTypes = getSupportedTypes(exportConfig.format);

  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">
            <Download className="w-6 h-6 text-blue-600" />
            <h2 className="text-lg font-semibold text-gray-900">数据导出</h2>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
          >
            <XCircle className="w-5 h-5" />
          </button>
        </div>

        {/* 内容 */}
        <div className="flex-1 overflow-y-auto p-6 space-y-6">
          {/* 导出格式选择 */}
          <div>
            <h3 className="text-sm font-medium text-gray-900 mb-3">导出格式</h3>
            <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
              {Object.entries(formatConfigs).map(([format, config]) => {
                const Icon = config.icon;
                return (
                  <button
                    key={format}
                    onClick={() => {
                      updateConfig({ format: format as ExportFormat });
                      // 如果当前类型不支持新格式，切换到支持的第一个类型
                      const newSupportedTypes = config.supports as ExportType[];
                      if (!newSupportedTypes.includes(exportConfig.type)) {
                        updateConfig({ type: newSupportedTypes[0] });
                      }
                    }}
                    className={`p-3 border-2 rounded-lg text-left transition-all ${
                      exportConfig.format === format
                        ? 'border-blue-500 bg-blue-50'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <div className="flex items-center space-x-2 mb-1">
                      <Icon className="w-4 h-4 text-blue-600" />
                      <span className="font-medium text-sm">{config.label}</span>
                    </div>
                    <p className="text-xs text-gray-600">{config.description}</p>
                  </button>
                );
              })}
            </div>
          </div>

          {/* 导出类型选择 */}
          <div>
            <h3 className="text-sm font-medium text-gray-900 mb-3">导出内容</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              {supportedTypes.map((type) => {
                const config = typeConfigs[type];
                const Icon = config.icon;
                return (
                  <button
                    key={type}
                    onClick={() => updateConfig({ type })}
                    className={`p-3 border-2 rounded-lg text-left transition-all ${
                      exportConfig.type === type
                        ? 'border-blue-500 bg-blue-50'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <div className="flex items-center space-x-2 mb-1">
                      <Icon className="w-4 h-4 text-blue-600" />
                      <span className="font-medium text-sm">{config.label}</span>
                    </div>
                    <p className="text-xs text-gray-600">{config.description}</p>
                  </button>
                );
              })}
            </div>
          </div>

          {/* 导出选项 */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-sm font-medium text-gray-900">导出选项</h3>
              <button
                onClick={() => setShowAdvancedOptions(!showAdvancedOptions)}
                className="text-sm text-blue-600 hover:text-blue-800"
              >
                {showAdvancedOptions ? '隐藏高级选项' : '显示高级选项'}
              </button>
            </div>

            <div className="space-y-4">
              {/* 基本选项 */}
              <div className="grid grid-cols-2 gap-4">
                <label className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    checked={exportConfig.include_metadata}
                    onChange={(e) => updateConfig({ include_metadata: e.target.checked })}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700">包含元数据</span>
                </label>

                <label className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    checked={exportConfig.include_results}
                    onChange={(e) => updateConfig({ include_results: e.target.checked })}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700">包含执行结果</span>
                </label>

                <label className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    checked={exportConfig.include_logs}
                    onChange={(e) => updateConfig({ include_logs: e.target.checked })}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700">包含执行日志</span>
                </label>

                <label className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    checked={exportConfig.compression}
                    onChange={(e) => updateConfig({ compression: e.target.checked })}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700">启用压缩</span>
                </label>
              </div>

              {/* 高级选项 */}
              {showAdvancedOptions && (
                <div className="bg-gray-50 rounded-lg p-4 space-y-4">
                  {/* 日期范围 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      日期范围 (可选)
                    </label>
                    <div className="grid grid-cols-2 gap-2">
                      <input
                        type="date"
                        value={exportConfig.date_range?.start || ''}
                        onChange={(e) => updateConfig({
                          date_range: {
                            start: e.target.value,
                            end: exportConfig.date_range?.end || ''
                          }
                        })}
                        className="px-3 py-2 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                      />
                      <input
                        type="date"
                        value={exportConfig.date_range?.end || ''}
                        onChange={(e) => updateConfig({
                          date_range: {
                            start: exportConfig.date_range?.start || '',
                            end: e.target.value
                          }
                        })}
                        className="px-3 py-2 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                      />
                    </div>
                  </div>

                  {/* 密码保护 */}
                  <div>
                    <label className="flex items-center space-x-2 mb-2">
                      <input
                        type="checkbox"
                        checked={exportConfig.password_protection}
                        onChange={(e) => updateConfig({ password_protection: e.target.checked })}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="text-sm text-gray-700">密码保护</span>
                    </label>
                    {exportConfig.password_protection && (
                      <input
                        type="password"
                        placeholder="设置导出文件密码"
                        value={exportConfig.password || ''}
                        onChange={(e) => updateConfig({ password: e.target.value })}
                        className="w-full px-3 py-2 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500"
                      />
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* 导出预览 */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div className="flex items-start space-x-2">
              <Info className="w-5 h-5 text-blue-600 mt-0.5" />
              <div>
                <h4 className="text-sm font-medium text-blue-900">导出预览</h4>
                <p className="text-sm text-blue-700 mt-1">
                  将导出 {getEstimatedItemCount()} 个{currentTypeConfig.label}项目，
                  格式为 {currentFormatConfig.label}
                  {exportConfig.compression && '（压缩）'}
                  {exportConfig.password_protection && '（密码保护）'}
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* 底部操作栏 */}
        <div className="flex items-center justify-between p-6 border-t border-gray-200">
          <div className="text-sm text-gray-500">
            预计文件大小: {formatFileSize(getEstimatedItemCount() * 1024)}
          </div>
          
          <div className="flex items-center space-x-3">
            <button
              onClick={onClose}
              className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
            >
              取消
            </button>
            <button
              onClick={startExport}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
            >
              <Download className="w-4 h-4" />
              <span>开始导出</span>
            </button>
          </div>
        </div>

        {/* 导出任务列表 */}
        {activeTasks.length > 0 && (
          <div className="border-t border-gray-200 p-6">
            <h3 className="text-sm font-medium text-gray-900 mb-4">导出任务</h3>
            <div className="space-y-3">
              {activeTasks.map((task) => (
                <div key={task.id} className="border border-gray-200 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center space-x-3">
                      <currentFormatConfig.icon className="w-4 h-4 text-blue-600" />
                      <span className="font-medium text-sm">
                        {typeConfigs[task.config.type].label} - {formatConfigs[task.config.format].label}
                      </span>
                      {getStatusIcon(task.status)}
                    </div>
                    
                    {task.download_url && task.status === 'completed' && (
                      <a
                        href={task.download_url}
                        download
                        className="px-3 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors text-sm flex items-center space-x-1"
                      >
                        <Download className="w-3 h-3" />
                        <span>下载</span>
                      </a>
                    )}
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">
                        进度: {task.processed_items}/{task.total_items}
                      </span>
                      <span className="text-gray-600">
                        {task.progress}%
                      </span>
                    </div>
                    
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div 
                        className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                        style={{ width: `${task.progress}%` }}
                      />
                    </div>

                    {task.file_size && (
                      <div className="text-xs text-gray-500">
                        文件大小: {formatFileSize(task.file_size)}
                      </div>
                    )}

                    {task.error_message && (
                      <div className="text-xs text-red-600 bg-red-50 p-2 rounded">
                        {task.error_message}
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
