/**
 * 快速导出按钮组件
 * 
 * 提供快速导出功能的下拉菜单按钮
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useRef, useEffect } from 'react';
import { 
  Download, 
  ChevronDown, 
  FileText, 
  Database, 
  BarChart3,
  Archive,
  Settings
} from 'lucide-react';
import type { 
  WorkflowTemplate, 
  WorkflowExecutionRecord 
} from '../../types/workflow';

// 快速导出选项接口
interface QuickExportOption {
  id: string;
  label: string;
  description: string;
  icon: React.ComponentType<any>;
  format: string;
  type: string;
}

// 组件属性接口
interface QuickExportButtonProps {
  /** 选中的工作流模板 */
  selectedTemplates?: WorkflowTemplate[];
  /** 选中的执行记录 */
  selectedExecutions?: WorkflowExecutionRecord[];
  /** 导出回调 */
  onExport?: (option: QuickExportOption, data: any[]) => void;
  /** 打开完整导出器回调 */
  onOpenFullExporter?: () => void;
  /** 按钮大小 */
  size?: 'sm' | 'md' | 'lg';
  /** 是否禁用 */
  disabled?: boolean;
}

/**
 * 快速导出按钮组件
 */
export const QuickExportButton: React.FC<QuickExportButtonProps> = ({
  selectedTemplates = [],
  selectedExecutions = [],
  onExport,
  onOpenFullExporter,
  size = 'md',
  disabled = false
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // 快速导出选项
  const quickExportOptions: QuickExportOption[] = [
    {
      id: 'templates_json',
      label: '模板 (JSON)',
      description: '导出工作流模板为JSON格式',
      icon: FileText,
      format: 'json',
      type: 'templates'
    },
    {
      id: 'executions_csv',
      label: '执行记录 (CSV)',
      description: '导出执行记录为CSV表格',
      icon: Database,
      format: 'csv',
      type: 'executions'
    },
    {
      id: 'executions_excel',
      label: '执行记录 (Excel)',
      description: '导出执行记录为Excel工作簿',
      icon: BarChart3,
      format: 'excel',
      type: 'executions'
    },
    {
      id: 'results_zip',
      label: '执行结果 (ZIP)',
      description: '打包下载所有执行结果',
      icon: Archive,
      format: 'zip',
      type: 'results'
    }
  ];

  // 获取可用的导出选项
  const getAvailableOptions = (): QuickExportOption[] => {
    const options: QuickExportOption[] = [];
    
    if (selectedTemplates.length > 0) {
      options.push(quickExportOptions.find(opt => opt.id === 'templates_json')!);
    }
    
    if (selectedExecutions.length > 0) {
      options.push(
        quickExportOptions.find(opt => opt.id === 'executions_csv')!,
        quickExportOptions.find(opt => opt.id === 'executions_excel')!,
        quickExportOptions.find(opt => opt.id === 'results_zip')!
      );
    }
    
    return options.filter(Boolean);
  };

  // 处理点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 处理快速导出
  const handleQuickExport = async (option: QuickExportOption) => {
    setIsOpen(false);
    
    if (!onExport) return;

    // 根据导出类型准备数据
    let data: any[] = [];
    switch (option.type) {
      case 'templates':
        data = selectedTemplates;
        break;
      case 'executions':
      case 'results':
        data = selectedExecutions;
        break;
    }

    // 执行快速导出
    try {
      await performQuickExport(option, data);
      if (onExport) {
        onExport(option, data);
      }
    } catch (error) {
      console.error('快速导出失败:', error);
    }
  };

  // 执行快速导出
  const performQuickExport = async (option: QuickExportOption, data: any[]) => {
    // 根据格式生成导出数据
    let exportData: any;
    let filename: string;
    let mimeType: string;

    switch (option.format) {
      case 'json':
        exportData = JSON.stringify({
          export_type: option.type,
          export_time: new Date().toISOString(),
          count: data.length,
          data: data
        }, null, 2);
        filename = `${option.type}_${new Date().toISOString().split('T')[0]}.json`;
        mimeType = 'application/json';
        break;

      case 'csv':
        exportData = convertToCSV(data);
        filename = `${option.type}_${new Date().toISOString().split('T')[0]}.csv`;
        mimeType = 'text/csv';
        break;

      case 'excel':
        // 简化的Excel导出（实际应用中可能需要使用专门的库）
        exportData = convertToCSV(data);
        filename = `${option.type}_${new Date().toISOString().split('T')[0]}.csv`;
        mimeType = 'text/csv';
        break;

      case 'zip':
        // ZIP格式需要特殊处理，这里简化为JSON
        exportData = JSON.stringify({
          export_type: option.type,
          export_time: new Date().toISOString(),
          count: data.length,
          data: data
        }, null, 2);
        filename = `${option.type}_${new Date().toISOString().split('T')[0]}.json`;
        mimeType = 'application/json';
        break;

      default:
        throw new Error(`不支持的导出格式: ${option.format}`);
    }

    // 创建并下载文件
    const blob = new Blob([exportData], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  };

  // 转换为CSV格式
  const convertToCSV = (data: any[]): string => {
    if (data.length === 0) return '';

    // 获取所有字段名
    const fields = new Set<string>();
    data.forEach(item => {
      Object.keys(item).forEach(key => fields.add(key));
    });

    const fieldArray = Array.from(fields);
    
    // 生成CSV头部
    const header = fieldArray.join(',');
    
    // 生成CSV数据行
    const rows = data.map(item => {
      return fieldArray.map(field => {
        const value = item[field];
        if (value === null || value === undefined) return '';
        if (typeof value === 'object') return JSON.stringify(value);
        if (typeof value === 'string' && value.includes(',')) return `"${value}"`;
        return value;
      }).join(',');
    });

    return [header, ...rows].join('\n');
  };

  // 获取按钮样式类
  const getButtonClasses = () => {
    const baseClasses = 'inline-flex items-center border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors';
    
    switch (size) {
      case 'sm':
        return `${baseClasses} px-2 py-1 text-xs rounded`;
      case 'lg':
        return `${baseClasses} px-4 py-3 text-base rounded-lg`;
      default:
        return `${baseClasses} px-3 py-2 text-sm rounded-lg`;
    }
  };

  const availableOptions = getAvailableOptions();
  const hasData = selectedTemplates.length > 0 || selectedExecutions.length > 0;

  if (!hasData && !onOpenFullExporter) {
    return null;
  }

  return (
    <div className="relative" ref={dropdownRef}>
      <div className="flex">
        {/* 主导出按钮 */}
        <button
          onClick={() => {
            if (availableOptions.length === 1) {
              handleQuickExport(availableOptions[0]);
            } else if (onOpenFullExporter) {
              onOpenFullExporter();
            }
          }}
          disabled={disabled || (!hasData && !onOpenFullExporter)}
          className={`${getButtonClasses()} ${
            availableOptions.length > 1 ? 'rounded-r-none border-r-0' : ''
          } disabled:opacity-50 disabled:cursor-not-allowed`}
        >
          <Download className={`${size === 'sm' ? 'w-3 h-3' : 'w-4 h-4'} mr-1`} />
          <span>
            {availableOptions.length === 1 
              ? availableOptions[0].label 
              : hasData 
                ? `导出 (${selectedTemplates.length + selectedExecutions.length})`
                : '导出'
            }
          </span>
        </button>

        {/* 下拉按钮 */}
        {(availableOptions.length > 1 || onOpenFullExporter) && (
          <button
            onClick={() => setIsOpen(!isOpen)}
            disabled={disabled}
            className={`${getButtonClasses()} rounded-l-none border-l border-gray-300 px-2 disabled:opacity-50 disabled:cursor-not-allowed`}
          >
            <ChevronDown className={`${size === 'sm' ? 'w-3 h-3' : 'w-4 h-4'}`} />
          </button>
        )}
      </div>

      {/* 下拉菜单 */}
      {isOpen && (availableOptions.length > 1 || onOpenFullExporter) && (
        <div className="absolute right-0 mt-1 w-64 bg-white border border-gray-200 rounded-lg shadow-lg z-10">
          <div className="py-1">
            {/* 快速导出选项 */}
            {availableOptions.map((option) => {
              const Icon = option.icon;
              return (
                <button
                  key={option.id}
                  onClick={() => handleQuickExport(option)}
                  className="w-full px-4 py-2 text-left hover:bg-gray-50 flex items-start space-x-3"
                >
                  <Icon className="w-4 h-4 text-gray-500 mt-0.5" />
                  <div>
                    <div className="text-sm font-medium text-gray-900">
                      {option.label}
                    </div>
                    <div className="text-xs text-gray-500">
                      {option.description}
                    </div>
                  </div>
                </button>
              );
            })}

            {/* 分隔线 */}
            {availableOptions.length > 0 && onOpenFullExporter && (
              <div className="border-t border-gray-200 my-1" />
            )}

            {/* 完整导出器选项 */}
            {onOpenFullExporter && (
              <button
                onClick={() => {
                  setIsOpen(false);
                  onOpenFullExporter();
                }}
                className="w-full px-4 py-2 text-left hover:bg-gray-50 flex items-start space-x-3"
              >
                <Settings className="w-4 h-4 text-gray-500 mt-0.5" />
                <div>
                  <div className="text-sm font-medium text-gray-900">
                    高级导出
                  </div>
                  <div className="text-xs text-gray-500">
                    更多格式和自定义选项
                  </div>
                </div>
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
};
