/**
 * 简化的工作流导出模态框
 * 
 * 只导出工作流模板和执行环境，支持一键导入
 */

import React, { useState } from 'react';
import { X, Download, Upload, Package, CheckCircle, AlertCircle } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { save, open } from '@tauri-apps/plugin-dialog';
import type { WorkflowTemplate, WorkflowExecutionEnvironment } from '../../types/workflow';

interface SimpleExportModalProps {
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 关闭回调 */
  onClose: () => void;
  /** 选中的工作流模板 */
  selectedTemplates?: WorkflowTemplate[];
  /** 选中的执行环境 */
  selectedEnvironments?: WorkflowExecutionEnvironment[];
}

interface ExportPackage {
  version: string;
  exported_at: string;
  templates: WorkflowTemplate[];
  environments: WorkflowExecutionEnvironment[];
  metadata: {
    total_templates: number;
    total_environments: number;
    export_source: string;
  };
}

/**
 * 简化的工作流导出模态框组件
 */
export const SimpleExportModal: React.FC<SimpleExportModalProps> = ({
  isOpen,
  onClose,
  selectedTemplates = [],
  selectedEnvironments = []
}) => {
  const [isExporting, setIsExporting] = useState(false);
  const [exportStatus, setExportStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const [errorMessage, setErrorMessage] = useState<string>('');

  if (!isOpen) return null;

  // 导出工作流包
  const handleExport = async () => {
    try {
      setIsExporting(true);
      setExportStatus('idle');
      setErrorMessage('');

      // 选择保存位置
      const filePath = await save({
        defaultPath: `workflow_package_${new Date().toISOString().split('T')[0]}.json`,
        filters: [
          {
            name: '工作流包',
            extensions: ['json']
          }
        ]
      });

      if (!filePath) {
        setIsExporting(false);
        return;
      }

      // 准备导出数据
      const exportPackage: ExportPackage = {
        version: '1.0.0',
        exported_at: new Date().toISOString(),
        templates: selectedTemplates,
        environments: selectedEnvironments,
        metadata: {
          total_templates: selectedTemplates.length,
          total_environments: selectedEnvironments.length,
          export_source: 'MixVideo Desktop'
        }
      };

      // 调用后端导出API
      await invoke('export_workflow_package', {
        packageData: exportPackage,
        filePath
      });

      setExportStatus('success');
    } catch (error) {
      console.error('导出失败:', error);
      setExportStatus('error');
      setErrorMessage(error instanceof Error ? error.message : '导出失败');
    } finally {
      setIsExporting(false);
    }
  };

  // 导入工作流包
  const handleImport = async () => {
    try {
      setExportStatus('idle');
      setErrorMessage('');

      // 选择文件
      const filePath = await open({
        multiple: false,
        filters: [
          {
            name: '工作流包',
            extensions: ['json']
          }
        ]
      });

      if (!filePath) {
        return;
      }

      // 调用导入API
      const result = await invoke<{ success: boolean; message: string; imported_count: number }>('import_workflow_package');

      if (result.success) {
        setExportStatus('success');
        // 可以在这里刷新页面数据
        setTimeout(() => {
          onClose();
          window.location.reload(); // 简单的刷新方式
        }, 2000);
      } else {
        setExportStatus('error');
        setErrorMessage(result.message);
      }
    } catch (error) {
      console.error('导入失败:', error);
      setExportStatus('error');
      setErrorMessage(error instanceof Error ? error.message : '导入失败');
    }
  };

  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-md w-full">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-lg font-semibold text-gray-900">
            工作流导入导出
          </h2>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 rounded-lg"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 内容 */}
        <div className="p-6 space-y-6">
          {/* 导出部分 */}
          <div className="space-y-4">
            <div className="flex items-center space-x-2">
              <Package className="w-5 h-5 text-blue-600" />
              <h3 className="text-md font-medium text-gray-900">导出工作流包</h3>
            </div>
            
            <div className="bg-gray-50 rounded-lg p-4 space-y-2">
              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-600">工作流模板:</span>
                <span className="font-medium">{selectedTemplates.length} 个</span>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-600">执行环境:</span>
                <span className="font-medium">{selectedEnvironments.length} 个</span>
              </div>
            </div>

            <button
              onClick={handleExport}
              disabled={isExporting || (selectedTemplates.length === 0 && selectedEnvironments.length === 0)}
              className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center space-x-2"
            >
              <Download className="w-4 h-4" />
              <span>{isExporting ? '导出中...' : '导出工作流包'}</span>
            </button>
          </div>

          {/* 分隔线 */}
          <div className="border-t border-gray-200"></div>

          {/* 导入部分 */}
          <div className="space-y-4">
            <div className="flex items-center space-x-2">
              <Upload className="w-5 h-5 text-green-600" />
              <h3 className="text-md font-medium text-gray-900">导入工作流包</h3>
            </div>
            
            <p className="text-sm text-gray-600">
              选择之前导出的工作流包文件，一键导入所有工作流模板和执行环境。
            </p>

            <button
              onClick={handleImport}
              className="w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center justify-center space-x-2"
            >
              <Upload className="w-4 h-4" />
              <span>选择文件导入</span>
            </button>
          </div>

          {/* 状态显示 */}
          {exportStatus === 'success' && (
            <div className="flex items-center space-x-2 p-3 bg-green-50 border border-green-200 rounded-lg">
              <CheckCircle className="w-5 h-5 text-green-600" />
              <span className="text-sm text-green-700">操作成功完成！</span>
            </div>
          )}

          {exportStatus === 'error' && (
            <div className="flex items-start space-x-2 p-3 bg-red-50 border border-red-200 rounded-lg">
              <AlertCircle className="w-5 h-5 text-red-600 mt-0.5" />
              <div className="text-sm text-red-700">
                <div className="font-medium">操作失败</div>
                <div>{errorMessage}</div>
              </div>
            </div>
          )}
        </div>

        {/* 底部说明 */}
        <div className="px-6 py-4 bg-gray-50 border-t border-gray-200 rounded-b-lg">
          <div className="text-xs text-gray-500 space-y-1">
            <div>• 导出的工作流包包含完整的模板配置和环境设置</div>
            <div>• 可以在其他设备上一键导入，快速部署相同的工作流环境</div>
            <div>• 导入时会自动检查兼容性并处理冲突</div>
          </div>
        </div>
      </div>
    </div>
  );
};
